6>>>-2相当于6>>>30
因为6是int类型的,4byte,32bit,二进制表达为0x00000006
无符号右移-2相当于右移(32+(-2))==30
如果这里是16进制的数,比如0xFFFFFFFFFFFFFFFFL(-1的二进制补码形式,补码不懂的自行百度)
那么右移-2就应该等于右移62(64+(-2)),64的意思是long是8byte,64bit
下面就是对于移位的测试代码
public class BitSetTest {
public static void main(String[] args) {
/**
* 返回 11111111111111111111111111111111
*/
System.out.println(Integer.toBinaryString(-1));
/**
* 返回 11111111111111111111111111111100
* 右边空位用0补齐
*/
System.out.println(Integer.toBinaryString(-1 << 2));
/**
* 返回 11111111111111111111111111111111
* 这里还是返回-1,因为>>有符号,前面空的用1补齐
*/
System.out.println(Integer.toBinaryString(-1 >> 10));
/**
* 返回 1111111111111111111111
* 无符号右移前面用0补齐
*/
System.out.println(Integer.toBinaryString(-1 >>> 10));
/**
* 下面两个都返回true
*/
System.out.println(Integer.toBinaryString(-1 >>> -2).
equals(Integer.toBinaryString(-1 >>> 30)));
System.out.println(Long.toBinaryString(0xFFFFFFFFFFFFFFFFL >>> -2).
equals(Long.toBinaryString(0xFFFFFFFFFFFFFFFFL >>> 62)));
}
}
楼上 @胡星宇 的答案-2应该是0xFFFFFFFE(补码)而不是0xFFFE。
懂了没?