I'm without my Java reference book and I'm having a tough time finding an answer with Google.
What is the difference between the ">>" and ">>>" operators in Java?
int value = 0x0100;
int result = (value >> 8);
System.out.println("(value >> 8) = " + result); // Prints: "(value >> 8) = 1"
result = (value >>> 8);
System.out.println("(value >>> 8) = " + result); // Prints: "(value >>> 8) = 1"
Difference between >> and >>> operator. Both >> and >>> are used to shift the bits towards the right. The difference is that the >> preserve the sign bit while the operator >>> does not preserve the sign bit. To preserve the sign bit, you need to add 0 in the MSB.
The unsigned right shift operator ( >>> ) (zero-fill right shift) evaluates the left-hand operand as an unsigned number, and shifts the binary representation of that number by the number of bits, modulo 32, specified by the right-hand operand.
The >>> operator is the unsigned right bit-shift operator in Java. It effectively divides the operand by 2 to the power of the right operand, or just 2 here.
>> is the signed right shift operator. It shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. When you shift right two bits, you drop the two least significant bits.
Signed integers use the high-order bit to denote sign.
So >>
preserves the sign, while >>>
doesn't. This is why >>
is referred to as the arithmetic shift and >>>
is the logical shift.
This way, you can do (assuming 32-bit integers) the following:
-10 >> 1
yields -5 (0xFFFFFFF6 >> 1
yields 0xFFFFFFFB - notice the high-order bit stays the same.)-10 >>> 1
yields 2147483643 (0xFFFFFFF6 >>> 1
yields 0x7FFFFFFB - notice all of the bits were shifted, so the high-order bit is now zero. The number is no longer negative according to twos-complement arithemetic.)For positive integers, >>
and >>>
act the same, since the high-order bit is already zero.
It also explains why there is no need for a <<<
operator. Since the sign would be trashed by sliding the bits to the left, it would map to no reasonable arithmetic operation.
>>>
is logical shift, >>
is arithmetic shift.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With