I've seen >>
and >>>
before. What is the difference and when to use each?
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
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
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