Java中的整型

来自姬鸿昌的知识库
跳到导航 跳到搜索

怎样输出整型的二进制形式

public class Test {

    public static void main(String[] args) {

        System.out.printf("binary string of %d: %s\n", 7, Integer.toBinaryString(7));

        System.out.printf("binary string of %d: %s\n", -7, Integer.toBinaryString(-7));

    }

}
binary string of 7: 111
binary string of -7: 11111111111111111111111111111001

如果想要正数显示全 ,可以:

public class Test {

    public static void main(String[] args) {

        System.out.printf("binary string of %d: %s\n", 7, String.format("%32s", Integer.toBinaryString(7)).replace(' ', '0'));

        System.out.printf("binary string of %d: %s\n", -7, Integer.toBinaryString(-7));

    }

}
binary string of 7: 00000000000000000000000000000111
binary string of -7: 11111111111111111111111111111001

int 4个字节(byte),32位(bit),1个符号位(0-正,1-负),

正数

就是十进制转二进制,其余位(bit)为0;

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

22+21+20=4+2+1=7

负数

则是补码存储:

①十进制转为二进制得到:

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

②然后取反码,再得到:

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 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0

③反码再+1,得到补码:

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 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1

④最后,首位(bit)是符号,值为二进制的1,表示负数:

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

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

怎么验证呢?