views:

1207

answers:

2

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"

+6  A: 
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)));
  }
}
John Meagher
I get:java.lang.NumberFormatException: For input string: "BF800000"
apalopohapa
When testing:Float.intBitsToFloat(Integer.valueOf("BF800000",16).intValue());I get the exception:java.lang.NumberFormatException: For input string: "BF800000"
apalopohapa
It's overflowing an int. Switching it to Long.valueOf(myString, 16) doesn't throw the exception, but results in -1.0 instead of 10.0. Are you sure 10.0 is the correct result?
John Meagher
that number is too big maybe? try using Long instead of integer.
Victor
i'm with john here, i'm getting -1.0 not 10.0
Victor
Confirmed 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
Also, 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
Also, 10.0 converts to "41200000"
John Meagher
Hi, yes, "BF800000" is -1.0, and using Long removes the exception. Thanks!
apalopohapa
+1  A: 

You need to convert the hex value to an int (left as an exercise) and then use Float.intBitsToFloat(int)

Jherico