Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
user1365914 Avatar asked Nov 28 '25 06:11

user1365914


1 Answers

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

like image 71
kichik Avatar answered Nov 30 '25 19:11

kichik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!