C 中的有符号与无符号 int
我是 C 初学者,需要快速澄清有关整数的问题。
当您将某些内容转换为 int(32 位)时,一半的位会分配给负整数。因此,如果你知道你总是有正整数,那么将某些东西转换为无符号整数应该最大化你的正位,因此当你知道输出总是为正时更有意义。这是真的吗?
谢谢你!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一半的位分配给负整数
这个说法不正确,一位分配给常规整数的符号。但是,您的假设是正确的。如果你确定数字是正数,使用
unsigned int
将允许你访问[0,2^32)范围内的数字,而常规int将只允许[-(2^31 ),2^31-1],由于您不需要负值,因此它会留下较少的正数。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.不是一半位,只是一个位转换为值的一半。也不是铸造而是声明:如果你铸造你正在重新解释的东西,这不会给你额外的范围,它只会给你一个潜在的与原始用户预期的价值不同。
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.
仅使用一位来识别该数字是正数还是负数。
转换为无符号可能有意义,也可能没有意义。有时最好让调试器等显示负数,以使您意识到您的数字已超出范围。
在比较无符号数时尤其需要小心——许多循环未能终止,因为倒计时值是无符号的并且比较是 for << 0。
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.
一位用于 +/-,而不是一半。使用无符号数可以将正值的范围扩大到带符号的等值范围的两倍。
One bit is used for +/-, not half. Using unsigned numbers gives you double the range of positive values vs. the signed equivalent.