10

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"

2 Answers 2

26
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)));
  }
}
Sign up to request clarification or add additional context in comments.

9 Comments

I get: java.lang.NumberFormatException: For input string: "BF800000"
When testing: Float.intBitsToFloat(Integer.valueOf("BF800000",16).intValue()); I get the exception: java.lang.NumberFormatException: For input string: "BF800000"
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?
that number is too big maybe? try using Long instead of integer.
i'm with john here, i'm getting -1.0 not 10.0
|
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.