Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between bitwise shift with 2 arrows and 3 arrows? [duplicate]

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

like image 386
happygilmore Avatar asked Mar 10 '14 17:03

happygilmore


2 Answers

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
like image 56
mttdbrd Avatar answered Oct 15 '22 12:10

mttdbrd


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

like image 21
Pat Butkiewicz Avatar answered Oct 15 '22 10:10

Pat Butkiewicz