Advertisements
Hi,
Here is the answer.
">>" is a signed right shift, while ">>>" is an unsigned right shift. What this means is that if you use a signed shift on a negative number, the result will still be negative. Signed right shifting by one is equivalent to dividing by two, even if the number is negative.
Unsigned shifting, on the other hand, ignores the sign of the number, and unsigned right shifting a negative number will result in a positive number -- which is why you generally shouldn't use the unsigned shift unless you are considering your number as unsigned.
The reason for the difference is that bytes, shorts, ints, and longs are all stored in two's-complement form (i.e. as signed numbers). This means, among other things, that the most significant bit is the sign bit, so that if the sign bit is 0 the number is positive, and if the sign bit is 1 the number is negative. If you want to divide a signed number by two by shifting it right, you have to retain the sign bit.
Another way of thinking about the difference between the operators is that the signed shift fills from the left with the sign bit (0 or 1), and the unsigned shift zero-fills from the left.
Thanks.