Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

bit-shift

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;
}
like image 866
Frank V Avatar asked Jun 26 '09 01:06

Frank V


1 Answers

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.

like image 157
David Johnstone Avatar answered Sep 28 '22 12:09

David Johnstone