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"
We can convert String to float in java using Float. parseFloat() method.
In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.
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.
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).
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)));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With