有人可以解释为什么我要输出这些输出吗?
我是c的新手。
我的问题。
为什么当值为正时,为什么有些数字最终会呈负?
I am new to c.
My Question.
Why do some numbers end up negative when the value was positive?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是您看到的输出的解释。
二进制中的1000是1111101000(10位),并在
int
(签名的32位)中存储在无符号char
(具有8位),The,顶部被“切断”。因此,您可以得到:
11101000
是232
在十进制中。作为一个(签名的)字符,由于设置了第一个(符号)位,因此将位解释为负数,在这种情况下为-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 is232
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.