Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

signed vs unsigned int in C

Tags:

c

int

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!

like image 784
dmubu Avatar asked Dec 03 '22 01:12

dmubu


1 Answers

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.

like image 77
amit Avatar answered Dec 18 '22 03:12

amit