Java 使用Float.floatToIntBits()然后使用Integer.toBinaryString()会导致混淆结果
我想了解浮点运算是如何工作的。当我运行此代码时 :Java 使用Float.floatToIntBits()然后使用Integer.toBinaryString()会导致混淆结果,java,floating-point,Java,Floating Point,我想了解浮点运算是如何工作的。当我运行此代码时 : float number = 3.0f; int bits = Float.floatToIntBits(number); System.out.println(Integer.toBinaryString(bits)); 我明白了 : 1000000010000000000000000000000 但是3的正确二进制格式应该是(根据 ): 为什么println在这里不显示符号位(0) 编辑 : 最初,我使用的是Long.toBinary
float number = 3.0f;
int bits = Float.floatToIntBits(number);
System.out.println(Integer.toBinaryString(bits));
我明白了 :
1000000010000000000000000000000
但是3的正确二进制格式应该是(根据 ):
为什么println在这里不显示符号位(0)
编辑 : 最初,我使用的是Long.toBinaryString
而不是Integer.toBinaryString
我会得到这样的结果 :
float number = -3.0f;
int bits = Float.floatToIntBits(number);
System.out.println(Long.toBinaryString(bits));
输出 :
1111111111111111111111111111111111000000010000000000000000000000
但是使用Integer.toBinaryString
返回-3.0f
:
11000000010000000000000000000000
Integer::toBinaryString
最多不会添加32位的零
int x = 0b_000001;
System.out.println(Integer::toBinaryString(x));
结果是1
,而不是000…0001
(32位)
标题零被省略。只需要一些格式 :
float number = 3.0f;
int bits = Float.floatToIntBits(number);
String representation = Integer.toBinaryString(bits);
representation = String.format("%32s", representation).replace(' ', '0');
只是
长。toBinaryString()
将0放在前面。您可以看到,与从转换器中获得的数字相比,有一个数字少。转换没有问题,只是显示错误。由于已关闭,因此无法投票支持duplicate,但此问题实际上是此问题的重复:
float number = 3.0f;
int bits = Float.floatToIntBits(number);
String representation = Integer.toBinaryString(bits);
representation = String.format("%32s", representation).replace(' ', '0');