Search code examples
c++bit-manipulationbitwise-not

How does bitwise not operation give negative value


I want to see how bitwise NOT works through a simple example:

int x = 4;
int y;
int z;
y = ~(x<<1);
z =~(0x01<<1);
cout<<"y = "<<y<<endl;
cout<<"z = "<<z<<endl;

This results in y = -9 and z = -3. I don't see how this happen. Anyone can educate me a bit?


Solution

  • (x<<1) will shift the bits one, so

    00000000 00000000 00000000 00000100
    

    will become:

    00000000 00000000 00000000 00001000
    

    Which is the representation of 8. Then ~ will invert all the bits such that it becomes:

    11111111 11111111 11111111 11110111
    

    Which is the representation of -9.


    0x01 is

    00000000 00000000 00000000 00000001
    

    in binary, so when shifted once becomes:

    00000000 00000000 00000000 00000010
    

    And then when ~ is applied we get:

    11111111 11111111 11111111 11111101
    

    Which is -3 in binary