C 中的无符号十六进制常量?
C 是否将十六进制常量(例如0x23FE
)视为有符号整数或无符号整数?
Does C treat hexadecimal constants (e.g. 0x23FE
) as signed or unsigned integers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
C 是否将十六进制常量(例如0x23FE
)视为有符号整数或无符号整数?
Does C treat hexadecimal constants (e.g. 0x23FE
) as signed or unsigned integers?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
数字本身始终被解释为非负数。十六进制常量没有符号或任何固有的方式来表达负数。常量的类型是其中第一个可以表示其值的类型:
The number itself is always interpreted as a non-negative number. Hexadecimal constants don't have a sign or any inherent way to express a negative number. The type of the constant is the first one of these which can represent their value:
它将它们视为 int 文字(基本上,作为有符号 int!)。要编写无符号文字,只需在末尾添加
u
即可:It treats them as
int
literals(basically, as signed int!). To write an unsigned literal just addu
at the end:根据cppreference,十六进制文字的类型是第一个类型以下列表适合该值。
所以这取决于你的数字有多大。如果您的数字小于
INT_MAX
,则它的类型为int
。如果您的数字大于INT_MAX
但小于UINT_MAX
,则它的类型为unsigned int
,依此类推。由于
0x23FE
小于INT_MAX
(即0x7FFF
或更大),因此它的类型为int
。如果您希望它是无符号的,请在数字末尾添加一个
u
:0x23FEu
。According to cppreference, the type of the hexadecimal literal is the first type in the following list in which the value can fit.
So it depends on how big your number is. If your number is smaller than
INT_MAX
, then it is of typeint
. If your number is greater thanINT_MAX
but smaller thanUINT_MAX
, it is of typeunsigned int
, and so forth.Since
0x23FE
is smaller thanINT_MAX
(which is0x7FFF
or greater), it is of typeint
.If you want it to be unsigned, add a
u
at the end of the number:0x23FEu
.