How to convert hex string to float in Java?
21,668
Solution 1
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)));
}
}
Solution 2
You need to convert the hex value to an int (left as an exercise) and then use Float.intBitsToFloat(int)
Related videos on Youtube
Author by
apalopohapa
Updated on May 19, 2020Comments
-
apalopohapa almost 4 years
How to convert hexadecimal string to single precision floating point in Java?
For example, how to implement:
float f = HexStringToFloat("BF800000"); // f should now contain -1.0
I ask this because I have tried:
float f = (float)(-1.0); String s = String.format("%08x", Float.floatToRawIntBits(f)); f = Float.intBitsToFloat(Integer.valueOf(s,16).intValue());
But I get the following exception:
java.lang.NumberFormatException: For input string: "bf800000"
-
apalopohapa almost 15 yearsI get: java.lang.NumberFormatException: For input string: "BF800000"
-
apalopohapa almost 15 yearsWhen testing: Float.intBitsToFloat(Integer.valueOf("BF800000",16).intValue()); I get the exception: java.lang.NumberFormatException: For input string: "BF800000"
-
Victor almost 15 yearsthat number is too big maybe? try using Long instead of integer.
-
Victor almost 15 yearsi'm with john here, i'm getting -1.0 not 10.0
-
John Meagher almost 15 yearsConfirmed the listed answer of 10.0 is not correct. The sample value is -1.0. Tested with above code and it works (now that it's Long instead of Integer).
-
John Meagher almost 15 yearsAlso, if my memory is working right, the top bit in an IEEE-754 float is the sign bit so the sample would have to be a negative number.
-
John Meagher almost 15 yearsAlso, 10.0 converts to "41200000"
-
apalopohapa almost 15 yearsHi, yes, "BF800000" is -1.0, and using Long removes the exception. Thanks!