为什么在char变量中存储255在C中赋值为-1? [英] Why stores 255 in a char variable give its value -1 in C?
问题描述
我正在读一本C书,并且有一篇文章,作者提到:
如果ch(一个char变量)签名类型,然后在ch变量中存储255的值为-1
。
假设8位 char
s,实际上是实现定义的行为。然而,大多数实现只是存储位模式,其中对于255是
< 0xFF 。使用二进制补码解释,作为有符号的8位整数,即
-1
的位模式。在一个稀有的补码结构上,这将是负零或陷阱表示的位模式,具有符号和幅度,它将是 -127
。 如果两个假设(signedness和8位 char
s)中的任何一个不成立, be¹255,因为255可以表示为一个无符号的8位整数或者是一个超过8位的有符号(或无符号)整数。
code> CHAR_BIT 至少为8,它可能会更大。
I am reading a C book, and there is a text the author mentioned:
"if ch (a char variable) is a signed type, then storing 255 in the ch variable gives it the value -1
".
Can anyone elaborate on that?
Assuming 8-bit char
s, that is actually implementation-defined behaviour. The value 255 cannot be represented as a signed 8-bit integer.
However, most implementations simply store the bit-pattern, which for 255 is 0xFF
. With a two's-complement interpretation, as a signed 8-bit integer, that is the bit-pattern of -1
. On a rarer ones'-complement architecture, that would be the bit pattern of negative zero or a trap representation, with sign-and-magnitude, it would be -127
.
If either of the two assumptions (signedness and 8-bit char
s) doesn't hold, the value will be¹ 255, since 255 is representable as an unsigned 8-bit integer or as a signed (or unsigned) integer with more than 8 bits.
¹ The standard guarantees that CHAR_BIT
is at least 8, it may be greater.
这篇关于为什么在char变量中存储255在C中赋值为-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!