1's complement using ~ in C/C++

user2912611 picture user2912611 · Jun 1, 2014 · Viewed 51.7k times · Source

I am using Visual Studio 2013.
Recently I tried the ~ operator for 1's complement:

int a = 10;
cout << ~a << endl;

Output is -11

But for

unsigned int a = 10;
cout << ~a << endl;

the output is 4294967296

I don't get why the output is -11 in the case of signed int. Please help me with this confusion.

Answer

Ivan Kuckir picture Ivan Kuckir · Jun 1, 2014

When you put number 10 into 32-bit signed or unsigned integer, you get

0000 0000  0000 0000  0000 0000  0000 1010

When you negate it, you get

1111 1111  1111 1111  1111 1111  1111 0101

These 32 bits mean 4294967285 as an unsigned integer, or -11 as a signed integer (your computer represents negative integers as Two's complement). They can also mean a 32-bit floating point number or four 8-bit characters.

Bits don't have any "absolute" meaning. They can represent anything, depending on how you "look" at them (which type they have).