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 = 01 10000000000000000000000000000000 >>> 0 = 100000000000000000000000000000002 11111111111111111111111110011101 & 10000000000000000000000000000000 = 100000000000000000000000000000003 10000000000000000000000000000000 >>> (31 - 0) = 000000000000000000000000000000014 输出00000000000000000000000000000001,屏显“1”i = 11 10000000000000000000000000000000 >>> 1 = 010000000000000000000000000000002 11111111111111111111111110011101 & 01000000000000000000000000000000 = 010000000000000000000000000000003 10000000000000000000000000000000 >>> (31 - 1) = 000000000000000000000000000000014 输出00000000000000000000000000000001,屏显“1”……i = 301 10000000000000000000000000000000 >>> 30 = 000000000000000000000000000000102 11111111111111111111111110011101 & 00000000000000000000000000000010 = 000000000000000000000000000000003 00000000000000000000000000000000 >>> (31 - 30) = 000000000000000000000000000000004 输出00000000000000000000000000000000,屏显“0”i = 311 10000000000000000000000000000000 >>> 31 = 000000000000000000000000000000012 11111111111111111111111110011101 & 00000000000000000000000000000001 = 000000000000000000000000000000013 00000000000000000000000000000001 >>> (31 - 31) = 000000000000000000000000000000014 输出00000000000000000000000000000001,屏显“1”根据循环过程可以看出(0x80000000 >>> i)的作用是mask,每次循环都与a做逻辑与操作,取a的第i位;对上条结果>>> 31 - i作用是把取出的a的第i位移到最末位。