如何在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”
答案 0 :(得分:16)
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)));
}
}
答案 1 :(得分:2)
您需要将十六进制值转换为int(左侧作为练习),然后使用Float.intBitsToFloat(int)