对于Java位移操作,有三种
- 左移(<<),规则 : 低位始终补0
- 右移(>>),规则: 正数符号位补0,负数符号位补1(符号位为最高位,0-正数,1-负数)
- 无符号右移(>>>),规则:符号位(最高位)始终补0
下面直接上一段代码:
@Test
public void testWeiYi(){
//右移比较简单
System.out.println(1L >> 1);
System.out.println(1L >> 65);
System.out.println(1L >>> 1);
System.out.println(1L >>> 65);
//long型
System.out.println("long 左移");
System.out.println(1L << 1);
System.out.println(1L << 65);
//int型
System.out.println("int 左移");
System.out.println(1 << 1);
System.out.println(1 << 33);
System.out.println(1 << 65);
//short型
System.out.println("short 左移");
System.out.println((short)((short)1 << 1));
System.out.println((short)((short)1 << 17));
System.out.println((short)((short)1 << 33));
System.out.println((short)((short)1 << 65));
//byte型
System.out.println("byte 左移");
System.out.println((byte)((byte)1 << 1));
System.out.println((byte)((byte)1 << 9));
System.out.println((byte)((byte)1 << 17));
System.out.println((byte)((byte)1 << 33));
System.out.println((byte)((byte)1 << 65));
}
运行结果:
有没有发现,左移竟然是循环移动的,不过对于byte,short,int都是转成int后,再循环移动
下面总结一下:
- 左移(<<),规则 : 低位始终补0, 左移是循环移动
- 右移(>>),规则: 正数符号位补0,负数符号位补1(符号位为最高位,0-正数,1-负数) 右移不是循环移动
- 无符号右移(>>>),规则:符号位(最高位)始终补0 右移不是循环移动
- 对于byte,short,int都是转成int后,再进行位移操作