这是 “C++ 编程完整指南”(Ulla Kirch-Prinz 和 Peter Prinz)中的示例
示例:
cout << dec << -1 << " " << hex << -1;
此语句会在 32 位系统上产生以下输出:
-1 ffffffff
谁能解释为什么第二个输出是ffffffff
?
我对书中的解释有疑问:
When octal or hexadecimal numbers are output, the bits of the number to be output are always interpreted as unsigned! In other words, the output shows the bit pattern of a number in octal or hexadecimal format.
最佳答案
那是因为大多数现代机器使用 two's complement有符号整数表示。
在二进制补码中,最高位用作符号位。如果已设置,则该数字被认为是负数,要获得它的绝对(正)值,您需要从 2N 中减去它,即取它的补码。
如果您有一个 8 位数字 00000001,它的补码将为 100000000-00000001 = 11111111(或 0xFF 十六进制)。所以-1在二进制形式中表示为全1。
这是一个非常方便的系统,因为您可以像数字无符号一样执行算术(让它们溢出),然后简单地将结果解释为有符号,它就是正确的。
关于c++ - C++中十六进制的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50523412/