Generally speaking, bit shifting (>> , <<
) allows us to divide / multiply by ^2
Example :
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
For negative numbers :
Likewise, -9 >> 2
yields -3
, because the sign is preserved:
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
But looking at >>>
which acts the same for positive numbers, but behaves differently for negative numbers :
Zero bits are shifted in from the left
I can't find any reason / usage for shifting 0
from the left ( which makes the whole number positive) from the left :
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
Question :
In what scenarios should I use >>>
? I don't understand why should I ever want to pad zeros from the left and mess my negative number.
>>>
operator,>>
preserves sign but>>>
not – Grijesh Chauhan>>
but when would you choose>>>
? – Royi Namir>>>
sometime we use in programming to for example I used here in my answer – Grijesh Chauhan11111111111111111111111111110111
. I may want to use as unsigned int0xfffffff7
and do the right shift to divide it. – L.B