Search code examples
cbit-manipulationbit-shift

Arithmetic Right Shift in C


In C, on a 32-bit machine, I was just wondering if 1>>31 returns -1 given 1 is a signed integer, since for 2's-complement, while doing right shift (arithmetic), sign bit is copied giving the result

1111 1111 1111 1111 1111 1111 1111 1111


Solution

  • No, the result will be zero in any conforming implementation.

    C99, 6.5.7/5 ("Bitwise shift operators") states:

    The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

    Since 1 is nonnegative, the result is the integral quotient of 1 / (2^31) which is obviously zero.