Reputation: 1143
I am a C beginner and needed a quick clarification regarding ints.
When you cast something as an int, which is 32 bits, half of the bits are allocated for negative integers. Thus, if you know that you will always have positive integers, casting something as an unsigned int should maximize your positive bits and thus make more sense when you know that output will always be positive. Is this true?
Thank you!
Upvotes: 4
Views: 6138
Reputation: 10758
One bit is used for +/-, not half. Using unsigned numbers gives you double the range of positive values vs. the signed equivalent.
Upvotes: 0
Reputation: 47759
Only one bit is used to identify whether the number is positive or negative.
Casting to unsigned may or may not make sense. Sometimes it's best to have debugger, et al, show the negative number, to make you aware that your number has gone out of range.
You especially need to be careful when comparing unsigned numbers -- many a loop has failed to terminate because the countdown value was unsigned and the compare was for < 0.
Upvotes: 3
Reputation: 178521
half of the bits are allocated for negative integers
This statement is not true, one bit is allocated to the sign for regular ints.
However, you are correct in your assumption. If you are positive the number is positive, using unsigned int
will allow you to access number in the range [0,2^32), while the regular int will only only allow [-(2^31),2^31-1], since you do not need the negative values, it leaves you with less positive numbers.
Upvotes: 8
Reputation: 93900
Not half the bits, just one bit which translates to half of the values. Also not casting but declaring: If you cast something you are reinterpreting it which doesn't give you additional range, it just gives you a potentially different value than the original user intended.
Upvotes: 4