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)

Share:
21,668

Related videos on Youtube

apalopohapa
Author by

apalopohapa

Updated on May 19, 2020

Comments

  • apalopohapa
    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
    apalopohapa almost 15 years
    I get: java.lang.NumberFormatException: For input string: "BF800000"
  • apalopohapa
    apalopohapa almost 15 years
    When testing: Float.intBitsToFloat(Integer.valueOf("BF800000",16).intValue‌​()); I get the exception: java.lang.NumberFormatException: For input string: "BF800000"
  • Victor
    Victor almost 15 years
    that number is too big maybe? try using Long instead of integer.
  • Victor
    Victor almost 15 years
    i'm with john here, i'm getting -1.0 not 10.0
  • John Meagher
    John Meagher almost 15 years
    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
    John Meagher almost 15 years
    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
    John Meagher almost 15 years
    Also, 10.0 converts to "41200000"
  • apalopohapa
    apalopohapa almost 15 years
    Hi, yes, "BF800000" is -1.0, and using Long removes the exception. Thanks!