9

I've seen >> and >>> before. What is the difference and when to use each?

happygilmore
  • 2,748
  • 4
  • 20
  • 33

2 Answers2

11

Others have provided the explanations. >>> shifts all the bits, even the sign bit (the MSB). >> keeps the sign bit in place and shifts all the others. This is best explained with some sample code:

int x=-64;

System.out.println("x >>> 3 = "  + (x >>> 3));
System.out.println("x >> 3 = "  + (x >> 3));
System.out.println(Integer.toBinaryString(x >>> 3));
System.out.println(Integer.toBinaryString(x >> 3));

Output is the following:

x >>> 3 = 536870904
x >> 3 = -8
11111111111111111111111111000
11111111111111111111111111111000
mttdbrd
  • 1,731
  • 11
  • 17
4

Double Arrows ">>" and Triple Arrows ">>>" are defined on 32-bit integers, so performing these on a variable will "convert" them so-to-speak from non-numbers, to numbers. Additionally, javascript numbers are stored as double precision floats, so these operations will also cause you to lose any precision bits higher than 32 . ">>" maintains the sign bit (result is a signed integer), while ">>>" does not (result is an unsigned integer).

http://msdn.microsoft.com/en-us/library/342xfs5s%28v=vs.94%29.aspx

For a much better explanation: https://stackoverflow.com/a/1822769/780399

Community
  • 1
  • 1
Pat Butkiewicz
  • 663
  • 5
  • 9