apalopohapa
apalopohapa

Reputation: 5183

How to convert hex string to float in Java?

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"

Upvotes: 10

Views: 24322

Answers (2)

John Meagher
John Meagher

Reputation: 24748

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: 26

Jherico
Jherico

Reputation: 29240

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

Upvotes: 2

Related Questions