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

10

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

例如,如何实现:

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

我询问此问题是因为我尝试过:

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"

2个回答

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

我得到了:java.lang.NumberFormatException: 输入字符串为"BF800000"。 - apalopohapa
它超出了int的范围。将其切换为Long.valueOf(myString, 16)不会抛出异常,但结果为-1.0而不是10.0。您确定10.0是正确的结果吗? - John Meagher
那个数字太大了吗?尝试使用Long而不是integer。 - Victor
确认列表中的答案10.0是不正确的。样本值为-1.0。使用上述代码进行测试,它可以工作(现在是Long而不是Integer)。 - John Meagher
另外,10.0转换为“41200000”。 - John Meagher
显示剩余4条评论

1

你需要将十六进制的值转换为整数(留作练习),然后使用Float.intBitsToFloat(int)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接