首页 > 代码库 > Java打印整数的二进制表示(代码与解析)

Java打印整数的二进制表示(代码与解析)

Java打印整数的二进制表示(代码与解析)

int a=-99;
for(int i=0;i<32;i++){
        int t=(a & 0x80000000>>>i)>>>(31-i);
        System.out.print(t);
}

拆分一下这段代码,要理解这个移位输出的问题还需要理解的以下内容:
* 0x80000000是数的十六进制表示,转成二进制表示为10000000000000000000000000000000
* 运算的优先级,移位运算高于逻辑运算,>>>高于&
* 位逻辑与运算 1&1 = 1 ,0&1 = 0
* >>>无符号右移,移出部分舍弃,左边位补0;

for循环的语句块的执行顺序:
1 0x80000000 无符号右移 i位;
2 a 和 1的结果做按位与;
3 2的结果无符号右移31-i位
4 输出3的结果

-99的机器数(补码)表示
11111111111111111111111110011101
循环过程演示:
i = 0
1 10000000000000000000000000000000 >>> 0 = 10000000000000000000000000000000
2 11111111111111111111111110011101 & 10000000000000000000000000000000 = 10000000000000000000000000000000
3 10000000000000000000000000000000 >>> (31 - 0) = 00000000000000000000000000000001
4 输出00000000000000000000000000000001,屏显“1”

i = 1
1 10000000000000000000000000000000 >>> 1 = 01000000000000000000000000000000
2 11111111111111111111111110011101 & 01000000000000000000000000000000 = 01000000000000000000000000000000
3 10000000000000000000000000000000 >>> (31 - 1) = 00000000000000000000000000000001
4 输出00000000000000000000000000000001,屏显“1”

……

i = 30
1 10000000000000000000000000000000 >>> 30 = 00000000000000000000000000000010
2 11111111111111111111111110011101 & 00000000000000000000000000000010 = 00000000000000000000000000000000
3 00000000000000000000000000000000 >>> (31 - 30) = 00000000000000000000000000000000
4 输出00000000000000000000000000000000,屏显“0”

i = 31
1 10000000000000000000000000000000 >>> 31 = 00000000000000000000000000000001
2 11111111111111111111111110011101 & 00000000000000000000000000000001 = 00000000000000000000000000000001
3 00000000000000000000000000000001 >>> (31 - 31) = 00000000000000000000000000000001
4 输出00000000000000000000000000000001,屏显“1”

根据循环过程可以看出
(0x80000000 >>> i)的作用是mask,每次循环都与a做逻辑与操作,取a的第i位;
对上条结果>>> 31 - i作用是把取出的a的第i位移到最末位。

Java打印整数的二进制表示(代码与解析)