在 2.7.1 整数常量部分,它说:
To illustrate some of the subtleties of integer constants, assume that type int uses a 16-bit twos-complement representation, type long uses a 32-bit twos-complement representation, and type long long uses a 64-bit twos-complement representation. We list in Table 2-6 some interesting integer constants...
An interesting point to note from this table is that integers in the range 2^15 through 2^16 - 1 will have positive values when written as decimal constants but negative values when written as octal or hexadecimal constants (and cast to type int).
但是,据我所知,2^15 - 2^16-1 范围内的整数在转换为 unsigned
类型时也具有正值。书错了吗?
最佳答案
在所描述的设置中,[32768,65535] 范围内的十进制文字具有类型 long int
, 并且该范围内的十六进制文字的类型为 unsigned int
.
因此,常量 0xFFFF
是一个 unsigned int
值为 65535,常量 65535
是签名long int
值为 65535。
我认为您的文字试图讨论案例:
(int)0xFFFF
(int)65535
现在,自 int
不能表示值 65535
这两者都会导致超出范围的转换,这是实现定义的(或者可能引发实现定义的信号)。
最常见的是(事实上,我听说过的所有 2 的补码系统),在这两种情况下,它将结合使用截断和重新解释,给出 -1
的值。 .
所以你引用的最后一段有点奇怪。 65535
和 0xFFFF
都是大的正数; (int)0xFFFF
和 (int)65535
都是(可能)都是负数;但是如果你投了一个而没有投另一个,那么你会得到一个不足为奇的差异。
关于c - "C: A reference manual"这本书中关于整数常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143918/