Search code examples
cbit-shift

Right shift operator in C


I got the following code:

int main(int argc, char *argv[])
{
    char c = 128;

    c = c >> 1;

    printf("c = %d\n", c);

    return 0;
}

Running the above code on Windows XP 32 bit, I got the result: -64. Why -64?


Solution

  • Because the char type is a signed 8-bit integer (in the implementation of C that you are using). If you try to store the value 128 in it, it will actually be -128.

    The bits for that would be:

    10000000
    

    Shifting a negative number will keep the sign bit set (as your implementation uses an arithmetic shift):

    11000000
    

    The result is -64.