5

If the shifted number is positive >>> and >> work the same.

If the shifted number is negative >>> fills the most significant bits with 1s whereas >> operation shifts filling the MSBs with 0.

Is my understanding correct?

If the negative numbers are stored with the MSB set to 1 and not the 2s complement way that Java uses the the operators would behave entirely differently, correct?

NullUserException
  • 83,810
  • 28
  • 209
  • 234
Murali
  • 1,495
  • 2
  • 15
  • 28
  • Possible duplicates: [Difference between >>> and >>](http://stackoverflow.com/q/2811319/1529630), [Java's >> versus >>> Operator?](http://stackoverflow.com/q/1034640/1529630) – Oriol Mar 29 '16 at 19:56

3 Answers3

8

The way negative numbers are represented is called 2's complement. To demonstrate how this works, take -12 as an example. 12, in binary, is 00001100 (assume integers are 8 bits though in reality they are much bigger). Take the 2's complement by simply inverting every bit, and you get 11110011. Then, simply add 1 to get 11110100. Notice that if you apply the same steps again, you get positive 12 back.

The >>> shifts in zero no matter what, so 12 >>> 1 should give you 00000110, which is 6, and (-12) >>> 1 should give you 01111010, which is 122. If you actually try this in Java, you'll get a much bigger number since Java ints are actually much bigger than 8 bits.

The >> shifts in a bit identical to the highest bit, so that positive numbers stay positive and negative numbers stay negative. 12 >> 1 is 00000110 (still 6) and (-12) >> 1 would be 11111010 which is negative 6.

Tyler
  • 21,762
  • 11
  • 61
  • 90
2

Definition of the >>> operator in the Java Language Specification:

The value of n>>>s is n right-shifted s bit positions with zero-extension. If n is positive, then the result is the same as that of n>>s; if n is negative, the result is equal to that of the expression (n>>s)+(2<<~s) if the type of the left-hand operand is int, and to the result of the expression (n>>s)+(2L<<~s) if the type of the left-hand operand is long.

matt b
  • 138,234
  • 66
  • 282
  • 345
1

Just the opposite, the >>> fills with zeros while >> fills with ones if the h.o bit is 1.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
  • Can you explain why `7>>>32=7`. I heard of circular shifts, but I thought that only applied to `>>`. Wouldn't `7>>>32` after 32 shifts just equal to zero? – Ian L Apr 04 '17 at 04:20
  • @IanLimarta: If the left hand side is an int, the shift amount is reduced mod 32. In your case, that means the shift amount is 0, which is effectively a no-op. See [the JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19) – President James K. Polk Apr 04 '17 at 10:29