views:

450

answers:

9

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"
+8  A: 

`>>> is logical shift, >> is arithmetic shift. http://en.wikipedia.org/wiki/Logical_shift

http://en.wikipedia.org/wiki/Arithmetic_shift

Budric
+6  A: 

From Java Notes: Bitwise Operators:

n >> p (right shift) Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.

Example: 5 >> 2 = 1

n >>> p (right shift) Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.

Example: -4 >>> 28 = 15

William Brendel
A: 

some info

the >> operator preserves the leftmost bits. The leftmost bits are filled with the previous content. This is to do with sign extension. In this case there is a 1 at the left and it is preserved. If you do not want to keep the 1 to the left, use the >>> operator which shifts 0's into the leftmost bits

akf
+2  A: 

The >> is an arithmetic shift, which preserves the sign bit in any 'vacant' bits. The other is a logical shift which fills the vacant spots with zeroes.

James
A: 

It has to do with signed value math. The >>> pills in zeros for the hight order bits, the >> preservers the sign bit and pulls it in.

BCS
A: 

The arithmetic shift >> is division by two for signed integers, while the logical shift >>> is division by two for unsigned numbers (if you interpret the bit pattern in a signed Java int as an unsigned integer).

starblue
+5  A: 

Signed integers use the high-order bit to denote sign.

So >> preserves the sign, while >>> doesn't.

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.

lavinio
+1 most useful answer
Bill K
+2  A: 
Michael Myers
A: 

For positive numbers, there is no difference. Negative (two's complement) numbers will be filled with zeros for >>> and ones for >>.

1010 0110 >>>2 = 0010 1001

1010 0110 >> 2 = 1110 1001

dhackner