Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java's >> versus >>> Operator? [duplicate]

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"
like image 646
Nate Avatar asked Jun 23 '09 19:06

Nate


People also ask

What is the difference between >> and >>> operator in Java?

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.

What is the use of >>> operator?

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.

What does >>> mean in Java?

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.

What does >> mean code?

>> 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.


2 Answers

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.

like image 52
lavinio Avatar answered Sep 28 '22 10:09

lavinio


>>> is logical shift, >> is arithmetic shift.

like image 32
Budric Avatar answered Sep 28 '22 11:09

Budric