“Java中的浮点型”的版本间的差异

来自姬鸿昌的知识库
跳到导航 跳到搜索
第1行: 第1行:
 
=== 怎样查看浮点型的二进制形式 ===
 
=== 怎样查看浮点型的二进制形式 ===
<syntaxhighlight lang="java">
+
以float为例:<syntaxhighlight lang="java">
 
public class Test2 {
 
public class Test2 {
  
第7行: 第7行:
 
         int intBits = Float.floatToIntBits(12345.12346f); //Bit Representation of the Float
 
         int intBits = Float.floatToIntBits(12345.12346f); //Bit Representation of the Float
 
         System.out.println(intBits); //1178657918
 
         System.out.println(intBits); //1178657918
         System.out.println(Integer.toBinaryString(intBits));
+
 
 +
        String binaryString = Integer.toBinaryString(intBits);
 +
        System.out.println(binaryString);
 +
 
 +
         System.out.println(binaryString.length());
  
 
     }
 
     }
第15行: 第19行:
 
1178657918
 
1178657918
 
1000110010000001110010001111110
 
1000110010000001110010001111110
 +
31
 
</syntaxhighlight>Float.floatToIntBits(float value) 方法返回的 int 型数据,就是 float 输入参数的二进制形式转换成对应的十进制值。
 
</syntaxhighlight>Float.floatToIntBits(float value) 方法返回的 int 型数据,就是 float 输入参数的二进制形式转换成对应的十进制值。
 +
  
 
=== 验证二进制字符串对应浮点数 ===
 
=== 验证二进制字符串对应浮点数 ===
 +
Java中浮点数也按照IEEE754标准存储,上面的 对于 float
 +
{| class="wikitable"
 +
!符号位
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
!
 +
|-
 +
!1
 +
!2
 +
!3
 +
!4
 +
!5
 +
!6
 +
!7
 +
!8
 +
!9
 +
!10
 +
!11
 +
!12
 +
!13
 +
!14
 +
!15
 +
!16
 +
!17
 +
!18
 +
!19
 +
!20
 +
!21
 +
!22
 +
!23
 +
!24
 +
!25
 +
!26
 +
!27
 +
!28
 +
!29
 +
!30
 +
2<sup>2</sup>
 +
!31
 +
2<sup>1</sup>
 +
!32
 +
2<sup>0</sup>
 +
|-
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|0
 +
|1
 +
|1
 +
|1
 +
|}

2022年11月12日 (六) 07:08的版本

怎样查看浮点型的二进制形式

以float为例:

public class Test2 {

    public static void main(String[] args) {

        int intBits = Float.floatToIntBits(12345.12346f); //Bit Representation of the Float
        System.out.println(intBits); //1178657918

        String binaryString = Integer.toBinaryString(intBits);
        System.out.println(binaryString);

        System.out.println(binaryString.length());

    }

}
1178657918
1000110010000001110010001111110
31

Float.floatToIntBits(float value) 方法返回的 int 型数据,就是 float 输入参数的二进制形式转换成对应的十进制值。


验证二进制字符串对应浮点数

Java中浮点数也按照IEEE754标准存储,上面的 对于 float

符号位
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

22

31

21

32

20

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1