Is right shift of a negative number arithmetic or logical?
Short answer: For unsigned types >> is always a logical shift (zeros come in from the left). For a negative signed value the result is implementation-defined; GCC, Clang and Arm compilers do an arithmetic shift that copies the sign bit, but portable code must not rely on it.
The two kinds of right shift
- Logical: fills the vacated high bits with 0.
0xF0000000u >> 4 == 0x0F000000u. - Arithmetic: fills them with copies of the sign bit, so the value stays negative.
-16 >> 2 == -4on GCC (0xFFFFFFF0 → 0xFFFFFFFC).
On Arm these are two different instructions, LSR and ASR. The compiler picks LSR for unsigned and ASR for signed operands.
Left shift is worse. Left-shifting a negative value, or shifting a 1 into or past the sign bit of a signed int, is undefined behaviour in C99/C11/C17. C23 made the representation two's complement but the overflow cases are still problems. An optimiser is allowed to assume undefined behaviour never happens and can delete code that depends on it.
Arithmetic shift is not exact division. -7 >> 1 gives -4 (rounds toward minus infinity) while -7 / 2 gives -3 (C rounds toward zero). That is why compilers emit extra fix-up instructions when you divide a signed value by a power of two.
Rule for interviews and production: do bit manipulation on uint8_t/uint16_t/uint32_t. If you must sign-extend a field, do it explicitly:
/* sign-extend the low 'bits' bits of x */
int32_t sign_extend(uint32_t x, unsigned bits)
{
uint32_t m = 1u << (bits - 1);
x &= (1u << bits) - 1u; /* bits < 32 */
return (int32_t)((x ^ m) - m);
}
Follow-up: "What does (int8_t)0x80 >> 1 give?" The int8_t is promoted to int (-128) first, then shifted: -64 on GCC. Integer promotion happens before every shift.