Reputation: 417
I am trying to convert this Hex Value C2DE70A4 in Android. This is the Code that I am writing for Conversion:
try {
String hexString = "C2DE70A4";
float myFloat = Float.intBitsToFloat(Integer.parseInt(hexString, 16));
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
But it is causing an Exception and telling me that Invalid int: "C2DE70A4"
Can anyone help me to make the Conversion? The Float value should be: -111.22
Thanks.
Upvotes: 2
Views: 1449
Reputation: 43391
0xC2DE70A4 in decimal is 3,269,357,732, but an int's max value is 2,147,483,647. That's why you can't parse it -- the parsed value is too big to fit in an int.
You should parse the string as a long, then cast it to an int , and finally call Float.intBitsToFloat
on that:
long asLong = Long.parseLong(hexString, 16);
int asInt = (int) asLong;
float myFloat = Float.intBitsToFloat(asInt);
// or, just
float myFloat = Float.intBitsToFloat((int)Long.parseLong(hexString, 16));
Detailed explanation:
Fundamentally, the problem is that C2DE70A4 represents an unsigned value, whereas ints in Java are signed. If you parse it as a long and then look at its bits (via Long.toBinaryString
), you'll see:
11000010110111100111000010100100
That's a 32-length string, because toBinaryString
omits leading 0s. So why didn't it fit in a 32-bit int? Because that binary string above represents an unsigned number. Or, more precisely, it's really shorthand for this signed, 64-bit, two's complement number:
0000000000000000000000000000000011000010110111100111000010100100
... which equals 3269357732 in decimal, which is out of the range of an int
because an int
is signed, meaning that the leftmost digit is the sign and not part of the number's magnitude (aka how "big" it is).
If you take that long
and cast it to an int
, it'll discard the leftmost 32 digits, leaving you with a 32-bit int 11000010110111100111000010100100
-- which corresponds to -1025609564 in decimal (again, in two's complement). If you then take that number and feed it to intBitsToFloat
, you'll get -111.22.
Upvotes: 5
Reputation: 704
public class Test {
public static void main (String[] args) {
String myString = "BF800000";
Long i = Long.parseLong(myString, 16);
Float f = Float.intBitsToFloat(i.intValue());
System.out.println(f);
System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
}
}
Upvotes: 1