Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 615
apalopohapa Avatar asked Jul 02 '09 00:07

apalopohapa


People also ask

Can we convert String to float in Java?

We can convert String to float in java using Float. parseFloat() method.

What converts the String value into float?

In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.

How are floats stored in hex?

On iOS devices, floating-point numbers are stored with a sign bit, a biased exponent, and an encoded significand. With 32-bit floats ( float ), the exponent is eight bits and is biased by 127, and the encoded significand is 23 bits.

Can you use hex in Java?

In Java code (as in many programming languages), hexadecimal nubmers are written by placing 0x before them. For example, 0x100 means 'the hexadecimal number 100' (=256 in decimal).


1 Answers

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)));
  }
}
like image 83
John Meagher Avatar answered Oct 07 '22 02:10

John Meagher