将较小整数的最大值分配给较大整数

发布于 2024-09-30 08:44:01 字数 503 浏览 2 评论 0原文

考虑以下代码:

 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一身仙ぐ女味 2024-10-07 08:44:01

对一元 ~ 的操作数执行整数提升,因此将 uint8_t(0) 提升为 int,然后将 ~ 被评估。它相当于

~(int)(uint8_t)0

您可以使用 std::numeric_limits::max() 获取类型可表示的最大值;如果类型是无符号的,您还可以将 -1 转换为该类型:

uint32_t x = (uint8_t)-1;

The integral promotions are performed on the operand of the unary ~, so the uint8_t(0) is promoted to int and then the ~ is evaluated. It's equivalent to

~(int)(uint8_t)0

You 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:

uint32_t x = (uint8_t)-1;
乖乖兔^ω^ 2024-10-07 08:44:01

在您的示例中,按位非运算符 (~) 在执行之前将其操作数提升为 int。然后通过赋值将其转换为unsigned int

以下是一些相关的代码示例,可以使这一点更加清晰:

uint8_t y = ~uint8_t(0);
uint32_t x = y;
std::cout << x << std::endl;

255

uint8_t y = uint8_t(0);
int z = ~y;
uint32_t x = z;
std::cout << x << std::endl;

4294967295

In your example, the bitwise not operator (~) is promoting its operand to an int before it executes. This is then converted to an unsigned int by the assignment.

Here are some related code samples that make this more clear:

uint8_t y = ~uint8_t(0);
uint32_t x = y;
std::cout << x << std::endl;

255

uint8_t y = uint8_t(0);
int z = ~y;
uint32_t x = z;
std::cout << x << std::endl;

4294967295

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文