What is the difference between >>>
and >>
operators in Java?
>>>
is unsigned-shift; it'll insert 0. >>
is signed, and will extend the sign bit.
The shift operators include left shift
<<
, signed right shift>>
, and unsigned right shift>>>
.The value of
n>>s
isn
right-shifteds
bit positions with sign-extension.The value of
n>>>s
isn
right-shifteds
bit positions with zero-extension.
System.out.println(Integer.toBinaryString(-1));
// prints "11111111111111111111111111111111"
System.out.println(Integer.toBinaryString(-1 >> 16));
// prints "11111111111111111111111111111111"
System.out.println(Integer.toBinaryString(-1 >>> 16));
// prints "1111111111111111"
To make things more clear adding positive counterpart
System.out.println(Integer.toBinaryString(121));
// prints "1111001"
System.out.println(Integer.toBinaryString(121 >> 1));
// prints "111100"
System.out.println(Integer.toBinaryString(121 >>> 1));
// prints "111100"
Since it is positive both signed and unsigned shifts will add 0 to left most bit.
1 >>> 32 == 1