Java:如何将二进制值的字符串转换为Float,反之亦然?
如何将12345.12346f的浮点值转换为二进制值的字符串,即“0011010101010101”,反之亦然?
我不确定它是你想要的,但是这里有一个解决方案,可以为浮点数提供IEEE 754浮点“双格式”位布局的二进制表示(它基本上是浮点数的内存表示forms):
int intBits = Float.floatToIntBits(yourFloat); String binary = Integer.toBinaryString(intBits);
对于相反的程序:
int intBits = Integer.parseInt(myString, 2); float myFloat = Float.intBitsToFloat(intBits);
工作样本:
class F { public static void main( String ... args ) { System.out.println( Integer.toBinaryString( Float.floatToIntBits(12345.12346f) ) ); } }
输出:
1000110010000001110010001111110
对于已签名的Floats,请使用Long或BigInteger来解析字符串。 通过int进行转换会导致32位首先的数字被解释为符号数字。 程序:
int intBits = Float.floatToIntBits(yourFloat); String binary = Integer.toBinaryString(intBits);
逆过程:
int intBits = new BigInteger(myString, 2).intValue(); // int intBits = (int) Long.parseLong(myString, 2); float myFloat = Float.intBitsToFloat(intBits);
您可以使用获取Java Float值的位表示
Float.floatToIntBits(float f);
完成后,你可以依次测试结果int的每一位,从最高位开始,找出是否设置,如果设置则写’1’,否则写’0’。