(-1 >> 1) == -1 - Why?

bit-shift, c

Solution

Because signed integers are represented in two's complement notation.

`-1` will be `11111111` (if it was an 8 bit number).

`-1 >> 1` evidently sign extends so that it remains `11111111`. This behaviour depends on the compiler, but for Microsoft, when shifting a signed number right (`>>`) the sign bit is copied, while shifting an unsigned number right causes a `0` to be put in the leftmost bit.

Problem

Why does `(-1 >> 1)` result in `-1`? I'm working in C, though I don't think that should matter. I can not figure out what I'm missing... Here is an example of a C program that does the calc: ``` #include <stdio.h> int main() { int num1 = -1; int num2 = (num1 >> 1); printf( "num1=%d", num1 ); printf( "\nnum2=%d", num2 ); return 0; } ```

Original source