I stumbled upon a question that asks whether you ever had to use bit shifting in real projects. I have used bit shifts quite extensively in many projects, however, I never had to use arithmetic bit shifting, i.e., bit shifting where the left operand could be negative and the sign bit should be shifted in instead of zeros. For example, in Java, you would do arithmetic bit shifting with the >>
operator (while >>>
would perform a logical shift). After thinking a lot, I came to the conclusion that I have never used the >>
with a possibly negative left operand.
As stated in this answer arithmetic shifting is even implementation defined in C++, so – in contrast to Java – there is not even a standardized operator in C++ for performing arithmetic shifting. The answer also states an interesting problem with shifting negative numbers that I was not even aware of:
+63 >> 1 = +31 (integral part of quotient E1/2E2)
00111111 >> 1 = 00011111
-63 >> 1 = -32
11000001 >> 1 = 11100000
So -63>>1
yields -32
which is obvious when looking at the bits, but maybe not what most programmers would anticipate on first sight. Even more surprising (but again obvious when looking at the bits) is that -1>>1
is -1
, not 0
.
So, what are concrete use cases for arithmetic right shifting of possibly negative values?
>>
is the arithmetic shift.>>>
is the logical shift. – Nocuousa/2
witha
being an integral type in almost all programming languages. – Vaasta(2n+1)/2 = n
then forn = -2
it fits. I however vaguely remember a solved bug in standard java involving>>
, binary search? – Honig>>
into a>>>
though, so it's really an example of when not to use>>
– Nocuous>>
on signed integers is division by a power of two, always rounding down. This is in contrast to the division operator /, which rounds towards zero. I've used >> on a microcontroller, both because it is faster, and because it avoids the discontinuity at zero. Yes, I checked the compiler manual that the implementation defined it in the way I expected. – Depurate