有人可以解释为什么我要输出这些输出吗?

发布于 2025-01-31 18:12:37 字数 84 浏览 2 评论 0原文

我是c的新手。

我的问题。

为什么当值为正时,为什么有些数字最终会呈负?

I am new to c.

My Question.

Why do some numbers end up negative when the value was positive?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

孤蝉 2025-02-07 18:12:37

这是您看到的输出的解释。
二进制中的1000是1111101000(10位),并在int(签名的32位)中存储在

无符号char(具有8位),The,顶部被“切断”。

因此,您可以得到:11101000232在十进制中。

作为一个(签名的)字符,由于设置了第一个(符号)位,因此将位解释为负数,在这种情况下为-24。

删除符号位时,1101000 = 104

MSB的“值”为128,因此您的计算机确实104-128 = -24

(请参阅 https://en.wikipedia.org/wiki/wiki/wiki/wiki/two%27s_complement

长期具有与int相同或更多的位,因此值不会改变。

Here is an explanation for the output you are seeing.
1000 in binary is 1111101000 (10 bits) and is stored in an int (signed 32 bits)

When you cast that to an unsigned char (that has 8 bits), the top bits get "cut off".

So you get: 11101000 which is 232 in decimal.

As a (signed) char, the bits get interpreted as a negative number because the first (sign) bit is set, which in this case is -24.

When you remove the sign bit, 1101000 = 104

The "value" of the MSB is 128, so your computer does 104 - 128 = -24.

(See https://en.wikipedia.org/wiki/Two%27s_complement)

A long has the same or more bits as an int so the value does not change.

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