I am trying to figure out how exactly arithmetic bit-shift operators work in C, and how it will affect signed 32-bit integers.
To make things simple, let\'s say we w
Bitwise shift operations are not defined for negative values
for '<<'
6.5.7/4 [...] If E1 has a signed type and nonnegative value, and E1×2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
and for '>>'
6.5.7/5 [...] If E1 has a signed type and a negative value, the resulting value is implementation- defined.
It's a waste of time to study the behaviour of these operations on signed numbers on a specific implementation, because you have no guarantee it will work the same way on any other implementation (an implementation is, for example, you compiler on your computer with your specific commad-line parameters).
It might not even work for an older or a newer version of the very same compiler. The compiler might even define those bits as random or undefined. This would mean that the very same code sequence could produce totally different results when used across your sources or even depend on things like assembly optimisation or other register usage. If encapsulated in a function it might not even produce the same result in those bits on two consecutive calls with the same arguments.
Considering only non-negative values, the effect of left shifting by 1 (expression << 1
) is the same as multpliying the expression by 2 (provided expression * 2 does not overflow) and the effect of right shifting by 1 (expression >> 1
) is the same as dividing by 2.