C 中的有符号与无符号 int

发布于 2024-12-06 09:22:22 字数 151 浏览 0 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

甜柠檬 2024-12-13 09:22:22

一半的位分配给负整数 这个说法不正确,一位分配给常规整数的符号。

但是,您的假设是正确的。如果你确定数字是正数,使用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.

花间憩 2024-12-13 09:22:22

不是一半,只是一个位转换为的一半。也不是铸造而是声明:如果你铸造你正在重新解释的东西,这不会给你额外的范围,它只会给你一个潜在的与原始用户预期的价值不同。

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.

-柠檬树下少年和吉他 2024-12-13 09:22:22

仅使用一位来识别该数字是正数还是负数。

转换为无符号可能有意义,也可能没有意义。有时最好让调试器等显示负数,以使您意识到您的数字已超出范围。

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

も让我眼熟你 2024-12-13 09:22:22

一位用于 +/-,而不是一半。使用无符号数可以将正值的范围扩大到带符号的等值范围的两倍。

One bit is used for +/-, not half. Using unsigned numbers gives you double the range of positive values vs. the signed equivalent.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文