In file data.hex, the data is given in hexadecimal form where the first digit of hexadecimal number is always less than 8. Eg.
01FC 04BF 04C0 04C1 04C2 24C3 04C4 34C5 ...
To parse this file and store the values in shrt[] array i have written this code
void read_hex_short(String filename, short[] shrt, int x, int y) throws Exception
{
String str;
Scanner s=new Scanner(new BufferedReader(new FileReader(filename)));
for(int i=0;i<height*width;i++)
{
str= s.next(); // i have tried str="0x"+s.next() but it didn't work
image[i]=(short)Integer.parseInt(str);
}
s.close();
}
But i am getting NumberFormatException which arises while passing the first string i.e. 01FC only.
How can i parse these hexadecimal values and store them in the shrt[] array?
You should be using Integer.parseInt(str, 16) to tell it to use hex.
You should also be aware that any values greater than 0x7FFF will end up being negative in your array: Java doesn't have any unsigned numeric types (unless you count char).
You can use Short.parseShort(str, 16) to parse HEX. This will avoid the need to cast it to short from an int.
Give parseInt method a radix parameter. Like this:
Integer.parseInt(str, 16)
Related
I'm trying to find a way to convert a char (Precondition is the char can only be '0' or '1') into an actual bit in Java. I'm not sure if Java has some built-in functionality for this, or if there is an algorithm that can be implemented to do so.
I need to implement the following class:
public void writeBit(char bit) {
//PRE:bit == '0' || bit == '1'
try {
} catch (IOException e) {
System.out.println(e);
}
}
I cannot change the method structure in any way. I am implementing Huffman Encoding and have an array of Strings that represent the encodings for every character within an input file. For example, 'A' or array[65] contains the String: "01011". So if I see the letter A in my file, I need to use writeBit to write out A's respective String to a binary file. Every time I reach 8 bits (one byte) I will call writeByte to send those 8 bits to the binary file, then reset some sort of counter variable to 0 and continue.
What I'm stuck on is how I am supposed to convert the char bit into an actual bit, so that it can be properly written out to a binary file.
Java does not have a primitive data type representing a single bit. On many hardware architectures, it is not even possible to access memory with that granularity.
When you say "an actual bit", then, I can only assume that you mean an integer value that is either 0 or 1, as opposed to char values '0' and '1'. There are numerous ways to perform such a conversion, among them:
byte the_bit = bit - '0';. This takes advantage of the fact that char is an integer type, and that the decimal digits zero and one are encoded in Java with consecutive character codes.
byte the_bit = (bit == '0') ? 0 : 1;. This just explicitly tests whether bit contains the value '0', evaluating to 0 if so or 1 if not.
It gets more complicated from there, for example:
byte the_bit = Byte.parseByte(String.valueOf(bit));. This converts the char to a string containing (only) that char, and then parses it as the string representation of a byte.
All of the above rely to one degree or another on the precondition given: that bit does not have any value other than '0' or '1'.
With that said, I think anything like this is probably the wrong approach for implementing a Huffman encoding, because Java Strings are an unlikely, very heavyweight, representation for the bit strings involved.
You can use Integer.parseInt(String s, int radix) or Integer.parseUnsignedInt(String s, int radix) with radix 2, to convert from a "binary digits string" to internal int java integer form.
public static void main(String[] args) {
int num = Integer.parseInt("101010", 2);
// print 42
System.out.println(num);
}
And reversely with method Integer.toBinaryString(int i) you can generate the binary string representation:
// print 101010
System.out.println(Integer.toBinaryString(42));
Similarly you can use Byte.parseByte(String s, int radix) to parse a byte:
public static void main(String[] args) {
byte num = Byte.parseByte("101010", 2);
// print 42
System.out.println(num);
}
Hello here i want to convert Byte array ie 0x3eb to short so i considered 0x3eb as a string and tried to convert to short but its throwing Numberformat Exception...someone please help me
import java.io.UnsupportedEncodingException;
public class mmmain
{
public static void main(String[] args) throws UnsupportedEncodingException
{
String ss="0x03eb";
Short value = Short.parseShort(ss);
System.out.println("value--->"+value);
}
}
Exception what im getting is
Exception in thread "main" java.lang.NumberFormatException:
For input string: "0x3eb" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:491)
at java.lang.Short.parseShort(Short.java:117)
at java.lang.Short.parseShort(Short.java:143)
at mmmain.main(mmmain.java:14)
even i tried converting 0x3eb to bytes by
byte[] bytes = ss.getBytes();
but i didnt found any implementation for parsing bytes to short.
Thanks in advance
See the doc of parseShort:
Parses the string argument as a signed decimal short. The characters
in the string must all be decimal digits, except that the first
character may be an ASCII minus sign '-' ('\u002D') to indicate a
negative value or an ASCII plus sign '+' ('\u002B') to indicate a
positive value.
The string to be parsed should only contain decimal characters and sign characters, it can not contains the 0x prefix.
Try:
String ss="3eb";
Short value = Short.parseShort(ss, 16);
Since the string value that you're using is a hexadecimal value, to convert it into short, you need to remove the 0x using a substring and pass the radix as below:
Short.parseShort(yourHexString.substring(2), 16)
Here 16 is the radix. More info in the doc here.
Update
Since the OP asked for some more clarification, adding the below info.
The short datatype can only have values between -32,768 and 32,767. It can't directly hold 0x3eb, but it can hold the equivalent decimal value of it. That's why when you parse it into the short variable and print, it shows 1003, which is the decimal equivalent of 0x3eb.
You have to cut "0x" from the beginning:
short.parseShort(yourHexString.Substring(2), 16)
Follow this document this may help you String to byte array, byte array to String in Java
i want to get the integer i.e decimal number corresponding to the binary string nc. However this does not happen despite using parseInt().
for eg if nc="11000101" then edcode is also having the same value instead of giving me the decimal representation of nc.
Can anyone please help
String codest="11010101";
char[] codear=codest.toCharArray();
codear[4]=codear[5];
String nc= new String(codear);
int edcode=Integer.parseInt(nc);
parseInt(String s, int radix)
Parses the string argument as a signed integer in the radix specified by the second argument.
From here.
Try this:
int edcode=Integer.parseInt(nc, 2);
int edcode=Integer.parseInt(nc, 2);
This will work
I have this for example:
0 10000101 00111100000000000000000
and want to convert this to decimal number.
So far, I already have the code to get the exponent part:
String[]hex={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
String[]binary={"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
String userInput="429E0000";
String result="";
for(int i=0;i<userInput.length();i++)
{
char temp=userInput.charAt(i);
String temp2=""+temp+"";
for(int j=0;j<hex.length;j++)
{
if(temp2.equalsIgnoreCase(hex[j]))
{
result=result+binary[j];
}
}
}
System.out.println(result);
int exponent = Integer.parseInt(result.substring(1,9),2)-127;
System.out.println(exponent);
Is there any in-built command in Java?
Yes, there is a built-in command, intBitsToFloat converts a 32-bit int to a float. You only have to parse your input as an int, the easier way - if your input is in hexadecimal format - would be to directly use base 16 in Integer.parseInt(), then intBitsToFloat converts that bit pattern to a float.
The Integer.ParseInteger(str, radix) will convert a binary digit string to an int ... if you use two as the radix.
However, Daniels answer gives you a better approach that avoids the need for any intermediate string representation of the number.
While writing a game for J2ME we ran into an issue using java.lang.Integer.parseInt()
We have several constant values defined as hex values, for example:
CHARACTER_RED = 0xFFAAA005;
During the game the value is serialized and is received through a network connection, coming in as a string representation of the hex value. In order to parse it back to an int we unsuccesfully tried the following:
// Response contains the value "ffAAA005" for "characterId"
string hexValue = response.get("characterId");
// The following throws a NumberFormatException
int value = Integer.parseInt(hexValue, 16);
Then I ran some tests and tried this:
string hexValue = Integer.toHexString(0xFFAAA005);
// The following throws a NumberFormatException
int value = Integer.parseInt(hexValue, 16);
This is the exception from the actual code:
java.lang.NumberFormatException: ffaaa005
at java.lang.Integer.parseInt(Integer.java:462)
at net.triadgames.acertijo.GameMIDlet.startMIDlet(GameMIDlet.java:109)
This I must admit, baffled me. Looking at the parseInt code the NumberFormatException seems to be thrown when the number being parsed "crosses" the "negative/positive boundary" (perhaps someone can edit in the right jargon for this?).
Is this the expected behavior for the Integer.parseInt function? In the end I had to write my own hex string parsing function, and I was quite displeased with the provided implementation.
In other words, was my expectation of having Integer.parseInt() work on the hex string representation of an integer misguided?
EDIT: In my initial posting I wrote 0xFFFAAA005 instead of 0xFFAAA005. I've since corrected that mistake.
The String you are parsing is too large to fit in an int. In Java, an int is a signed, 32-bit data type. Your string requires at least 36 bits.
Your (positive) value is still too large to fit in a signed 32-bit int.
Do realize that your input (4289372165) overflows the maximum size of an int (2147483647)?
Try parsing the value as a long and trim the leading "0x" off the string before you parse it:
public class Program {
public static void main(String[] args) {
String input = "0xFFFAAA005";
long value = Long.parseLong(input.substring(2), 16);
System.out.print(value);
}
}
I'm not a java dev, but I'd guess parseInt only works with integers. 0xFFFAAA005 has 9 hex digits, so it's a long, not an int. My guess is it's complaining because you asked it to parse a number that's bigger than it's result data type.
Your number seems to be too large to fit in an int, try using Long.parseLong() instead.
Also, the string doesn't seem to get parsed if you have 0x in your string, so try to cut that off.