c++ - char c = 255 的值转换为 int
问题描述
我的问题是关于 Stroustrup 的《C++ 编程语言,第 4 版》一书中的一段。他举了一个例子
char c = 255; // 255 is ‘‘all ones,’ ’ hexadecimal 0xFF
int i = c;
并解释如何在 char 已签名或未签名的机器上进行转换。
i 的值是多少?不幸的是,答案是不确定的。在具有 8 位字节的实现上,答案取决于扩展为 int 时“全为”字符位模式的含义。在 char 未签名的机器上,答案是 255。在 char 已签名的机器上,答案是 -1。
我的问题是为什么它会是-1,这不取决于机器上使用的二进制数表示吗?如果它使用一个补码,它不是 0(-0),如果是二进制补码,它不是 -1 吗?
解决方案
Quoting C++03 4.7/3:
If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.
Assuming bytes are 8 bits, this means that in theory you get one of the following:
-127
if signed magnitude computer.-0
if one's complement computer.-1
if two's complement computer.
The former two barely exist in the real world.