如何将十六进制字符串转换为Java中的浮点数?

2022-01-09 00:00:00 string floating-point hex java

Java中如何将十六进制字符串转换为单精度浮点数?

How to convert hexadecimal string to single precision floating point in Java?

例如如何实现:

float f = HexStringToFloat("BF800000");//f 现在应该包含 -1.0

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());

但我得到以下异常:

java.lang.NumberFormatException:对于输入字符串:bf800000"

java.lang.NumberFormatException: For input string: "bf800000"

推荐答案

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)));
  }
}

相关文章