posted 21 years ago
It all has everything to do with the way negative numbers are represented in binary form. A single byte can hold values from 0 to 11111111 (in binary, 255 in base10), but to hold negative numbers the leftmost bit was used to indicate the sign, so that a byte actually holds 0 to 01111111 (127 in base10). Any byte that starts with 1....... is a negative number.
To get a clearer idea how it works, if we list the numbers from the smallest (-128) to the largest (127) we have:
127 01111111
126 01111110
...
3 00000011
2 00000010
1 00000001
0 00000000
-1 11111111
-2 11111110
-3 11111101
-4 11111100
...
-128 10000000
Notice that -1 and 0 form a complementary pair. The same goes for 1 and -2, 2 and -3, etc. all the way up to 127 and -128.
Well, anyway 4 >> 2 is just
00000100 >> 2 or 00000001
but 4 >>> 2 is
00000100 >>> 2 or 00000001
But there's no difference, you object. True enough, but if -4 >> 2 this is
11111100 >> 2 or 11111111
but -4 >>> 2 is
11111100 >>> 2 is 00111111
To make this long story mercifully end, >> takes note of the leftmost bit when it is shifting, but >>> is always "zero-fill".
-anthony