三種移位運算
-
邏輯右移,沒有具體的數學意義>>>
-
算術右移,對正數,在不越界的情況下相當于除以二,對負數在不越界的情況下相當于餘數為1的除以二(通常負數除以正數,餘數應該為負數)>>
-
左移位,無論對于正數負數,在不越界的情況下相當于乘以二<<
移位會對所有位(包含符号位)進行移動,左移時低位補零,右移時,
>>
符号位移走後,高位補原符号位,
>>>
高位補零
示例
public class Demo {
public static void main(String[] args) {
int a = 11;
int b = -11;
System.out.println(Integer.toBinaryString(a) + "\n" + Integer.toBinaryString(b));
System.out.println((a>>1) + " " + Integer.toBinaryString(a>>1));
System.out.println((a<<1) + " " + Integer.toBinaryString(a<<1));
System.out.println((b>>1) + " " + Integer.toBinaryString(b>>1));
System.out.println((b>>>1) + " " + Integer.toBinaryString(b>>>1));
}
}
結果:
1011
11111111111111111111111111110101
5 101
22 10110
-6 11111111111111111111111111111010
2147483642 1111111111111111111111111111010