将较小整数的最大值分配给较大整数
考虑以下代码:
uint32_t x = ~uint8_t(0);
std::cout << x << std::endl;
现在,我完全期望它输出 255
,但它却输出 4294967295
。
我知道 C++ 中的整数提升,但我不明白为什么会发生这种情况。按照我的理解,表达式 ~uint8_t(0)
的计算结果应该是二进制的 1111 1111
。然后,~
运算符将通过符号扩展值,将类型提升为 int
(为了讨论起见,我假设它是 32 位)至0000 0000 0000 0000 0000 0000 1111 1111
。然后,应将此提升后的值分配给左值 x
,结果为 x == 255
。
但显然我没有正确理解这一点。我缺少什么?
Consider the following code:
uint32_t x = ~uint8_t(0);
std::cout << x << std::endl;
Now, I fully expected this to output 255
, but instead it output 4294967295
.
I'm aware of integer promotion in C++, but I can't understand why this would happen. The way I understand it, the expression ~uint8_t(0)
should evaluate to 1111 1111
in binary. The ~
operator will then cause the type to be promoted to an int
(which I'll assume is 32-bit for the sake of discussion), by sign extending the value to 0000 0000 0000 0000 0000 0000 1111 1111
. This promoted value should then be assigned to the lvalue x
, resulting in x == 255
.
But obviously I'm not understanding this correctly. What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对一元
~
的操作数执行整数提升,因此将uint8_t(0)
提升为int
,然后将~
被评估。它相当于您可以使用 std::numeric_limits::max() 获取类型可表示的最大值;如果类型是无符号的,您还可以将
-1
转换为该类型:The integral promotions are performed on the operand of the unary
~
, so theuint8_t(0)
is promoted toint
and then the~
is evaluated. It's equivalent toYou can get the maximum value representable by a type using
std::numeric_limits<T>::max()
; if the type is unsigned, you can also cast-1
to that type:在您的示例中,按位非运算符 (
~
) 在执行之前将其操作数提升为int
。然后通过赋值将其转换为unsigned int
。以下是一些相关的代码示例,可以使这一点更加清晰:
In your example, the bitwise not operator (
~
) is promoting its operand to anint
before it executes. This is then converted to anunsigned int
by the assignment.Here are some related code samples that make this more clear: