c - "C: A reference manual"这本书中关于整数常量

标签 c integer hex decimal octal

在 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 的值。 .

所以你引用的最后一段有点奇怪。 655350xFFFF都是大的正数; (int)0xFFFF(int)65535都是(可能)都是负数;但是如果你投了一个而没有投另一个,那么你会得到一个不足为奇的差异。

关于c - "C: A reference manual"这本书中关于整数常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143918/

相关文章:

c++ - (Qt C++) setw/setfill 等效?

perl - 在 Perl 中处理不同基数的命令行参数

lua - 为什么 lua 5.1 会错误地解释某些整数?

java - Kotlin 。如何格式化末尾为零的十进制数?

java - 将构造函数与 Integer 一起使用

decimal - String.Format 对十进制值感到窒息?

C程序在运行时崩溃

c - Linux 中是否有两个硬链接(hard link)连接到一个文件?

c - 如何正确重用套接字来发送UDP数据包?

c - C 中指向数组元素的指针