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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Both
4294967295(a.k.a.UINT_MAX) and-1have the same binary representation of0xFFFFFFFFor 32 bits all set to1. This is because signed numbers are represented using two’s complement. A negative number has its MSB (most significant bit) set to1and its value determined by flipping the rest of the bits, adding1and multiplying by-1. So if you have the MSB set to1and the rest of the bits also set to1, you flip them (get 32 zeros), add1(get1) and multiply by-1to 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) and1. Since there is only room for 32 bits, this will overflow and the result will be0as expected.See more at:
http://en.wikipedia.org/wiki/Two%27s_complement