Search code examples
cbit-manipulationsigned

How do I perform a signed right shift(>>) in c?


how do I perform a signed right shift in c? like -25 >> 3.

I tried like this: 10011001 >> 3 == 00010011

But the result is -4.


Solution

  • According to the standard 6.5.7p5

    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 /2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

    The result is implementation-defined, and you should look up how it is defined there.

    Assuming twos complement and signed right shift, -25 is 11100111, shifting it by 3 will lead to 11111100 which is -4.