简体   繁体   English

在C中签名vs unsigned int

[英]signed vs unsigned int in C

I am a C beginner and needed a quick clarification regarding ints. 我是C初学者,需要快速澄清有关整数。

When you cast something as an int, which is 32 bits, half of the bits are allocated for negative integers. 当你将某个东西作为一个32位的int转换时,一半的位被分配给负整数。 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! 谢谢!

half of the bits are allocated for negative integers This statement is not true, one bit is allocated to the sign for regular ints. half of the bits are allocated for negative integers这个语句不正确,一个位被分配给常规整数的符号。

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. 如果你是正数,那么使用unsigned int将允许你访问[0,2 ^ 32]范围内的数字,而常规int只允许[ - (2 ^ 31),2 ^ 31-1 ],因为你不需要负值,所以它会给你带来较少的正数。

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. 还没有铸造但在宣布 :如果你你重新诠释它的东西不给你额外的范围,它只是给你比原来的用户意图的潜在不同的值。

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. 在比较无符号数时尤其需要小心 - 许多循环未能终止,因为倒计时值是无符号的并且比较为<0。

One bit is used for +/-, not half. 一位用于+/-,而不是一半。 Using unsigned numbers gives you double the range of positive values vs. the signed equivalent. 使用无符号数字可以使正值的范围加倍,而不是有符号的等价。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM