How does bitwise not operation give negative value

7k Views Asked by At

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?

3

There are 3 best solutions below

4
GBlodgett On BEST ANSWER

(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

1
Christoph Lipka On

Whether an integer is positive or negative (the sign of the integer) is stored in a dedicated bit, the sign bit. The bitwise NOT affects this bit, too, so any positive number becomes a negative number and vice versa.

Note that "dedicated bit" is a bit of an oversimplification, as most contemporary computers do not use "sign and magnitude" representation (where the sign bit would just switch the sign), but "two's complement" representation, where the sign bit also affects the magnitude.

For example, the 8-bit signed integer 00000000 would be 0, but 10000000 (sign bit flipped) would be -128.

0
dzuda11 On

Well, there is a very long story behind.
To make it easier to understand let's use binary numbers.

x = 4 or x = 0b 0000 0000 0000 0000 0000 0000 0000 0100 because sizeOf(int) = 4
after x<<1 x = 0b 0000 0000 0000 0000 0000 0000 0000 1000 and after
~(x<<1) x = 0b 1111 1111 1111 1111 1111 1111 1111 0111.

and here begin complication. Since int is signed type it's mean that the first bit is a sign and the whole system is Two complemnt.

so x = 0b 1111 1111 1111 1111 1111 1111 1111 0111 is x = -9
and for example x = 0b 1111 1111 1111 1111 1111 1111 1111 1111 is x = -1 and x = 0b 0000 0000 0000 0000 0000 0000 0000 0010 is 2

Learn more about Two complemnt.