为什么在 char 变量中存储 255 在 C 中给出它的值 -1? [英] Why stores 255 in a char variable give its value -1 in C?
问题描述
我在看一本C书,有一段作者提到的文字:
I am reading a C book, and there is a text the author mentioned:
"如果 ch(一个 char 变量)是有符号类型,那么将 255 存储在 ch 变量中会得到值 -1
".
谁能详细说明一下?
推荐答案
假设是 8 位 char
,这实际上是实现定义的行为.值 255 不能表示为带符号的 8 位整数.
Assuming 8-bit char
s, that is actually implementation-defined behaviour. The value 255 cannot be represented as a signed 8-bit integer.
但是,大多数实现只是存储位模式,对于 255,位模式是 0xFF
.使用二进制补码解释,作为有符号的 8 位整数,即 -1
的位模式.在一个罕见的补码架构上,这将是负零的位模式或带有符号和大小的陷阱表示,它将是 -127
.
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
.
如果两个假设中的任何一个(有符号性和 8 位 char
s)不成立,则该值将为¹ 255,因为 255 可表示为无符号 8 位整数或超过 8 位的有符号(或无符号)整数.
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.
¹ 标准保证 CHAR_BIT
至少为 8,可能更大.
¹ The standard guarantees that CHAR_BIT
is at least 8, it may be greater.
这篇关于为什么在 char 变量中存储 255 在 C 中给出它的值 -1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!