gpt4 book ai didi

C++ - 按位不是 uchar 产生 int

转载 作者:可可西里 更新时间:2023-11-01 18:20:03 25 4
gpt4 key购买 nike

我对 C++ 对 unsigned char 按位应用 not 时的行为感到惊讶。

取二进制值01010101b,即0x55,或85。不在八位表示上按位应用应该产生 10101010b,即 0xAA170

但是,我无法在 C++ 中重现上述内容。以下简单断言失败。

assert(static_cast<unsigned char>(0xAAu) == ~static_cast<unsigned char>(0x55u));

我使用以下代码打印了 0x550xAA~0x55 的值(作为 uchar)。它揭示了按位非不做我期望它做的事情。

std::cout << "--> 0x55: " << 0x55u << ", 0xAA: " << 0xAAu << ", ~0x55: "
<< static_cast<unsigned>(~static_cast<unsigned char>(0x55u)) << std::endl;

--> 0x55: 85, 0xAA: 170, ~0x55: 4294967210

~0x55 打印的数字等于 11111111111111111111111110101010b,这是 0x55 的 32 位按位非。因此,即使我将输入显式转换为 unsigned char~ 运算符也在 32 位整数上运行。这是为什么?

我应用了另一个测试来查看 ~ 运算符返回的类型。结果是 unsigned char 输入上的 int:

template <class T>
struct Print;

// inside main()
Print<decltype(~static_cast<unsigned char>(0x55))> dummy;

产生以下编译器错误,表明结果的类型为 int

error: implicit instantiation of undefined template 'Print<int>'
Print<decltype(~static_cast<unsigned char>(0x55u))> dummy;

我做错了什么?或者,如何让 C++ 从 ~0x55 生成 0xAA

完整代码为 here

最佳答案

~ 的操作数执行整数提升,我们可以通过转到 draft C++ standard 看到这一点5.3.1 一元运算符 说(强调我的):

The operand of ˜ shall have integral or unscoped enumeration type; the result is the one’s complement of its operand. Integral promotions are performed. The type of the result is the type of the promoted operand [...]

4.5 部分介绍了积分促销 积分促销 并说:

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type;

为了完整起见,要查看 unsigned char 的等级小于 int 的等级,我们可以转到 4.13 部分 Integer转换等级表示:

The rank of a signed integer type shall be greater than the rank of any signed integer type with a smaller size.

和:

The rank of char shall equal the rank of signed char and unsigned char.

一种解决方案是将结果分配给 unsigned char,这是安全的,因为您不必担心有符号整数溢出。

正如 Ben Voigt 所指出的那样,它会符合 sizeof (int) == 1CHAR_BIT >= 32 的系统。在这种情况下,unsigned char 的级别将不低于 int,因此提升为 unsigned int。我们不知道有任何系统实际发生过这种情况。

关于C++ - 按位不是 uchar 产生 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26101257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com