如何在Java中将hex字符串转换为float?
如何在Java中将hex字符串转换为单精度浮点?
例如,如何实现:
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());
但我得到以下exception:
java.lang.NumberFormatException:对于输入字符串:“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))); } }
您需要将hex值转换为int(左侧作为练习),然后使用Float.intBitsToFloat(int)