Search code examples
coperatorsbit-manipulationtilde

Tilde C unsigned vs signed integer


For example:

unsigned int i = ~0;

Result: Max number I can assign to i

and

signed int y = ~0;

Result: -1

Why do I get -1? Shouldn't I get the maximum number that I can assign to y?


Solution

  • Both 4294967295 (a.k.a. UINT_MAX) and -1 have the same binary representation of 0xFFFFFFFF or 32 bits all set to 1. This is because signed numbers are represented using two's complement. A negative number has its MSB (most significant bit) set to 1 and its value determined by flipping the rest of the bits, adding 1 and multiplying by -1. So if you have the MSB set to 1 and the rest of the bits also set to 1, you flip them (get 32 zeros), add 1 (get 1) and multiply by -1 to finally get -1.

    This makes it easier for the CPU to do the math as it needs no special exceptions for negative numbers. For example, try adding 0xFFFFFFFF (-1) and 1. Since there is only room for 32 bits, this will overflow and the result will be 0 as expected.

    See more at:

    http://en.wikipedia.org/wiki/Two%27s_complement