无符号 8 位整数的左移运算

Left shift operation on an unsigned 8 bit integer

我正在尝试理解 C/C++ 中的移位运算符,但它们让我很吃力。

我有一个无符号的 8 位整数初始化为一个值,例如 1。

uint8_t x = 1;

根据我的理解,它在内存中表示为|0|0|0|0|0||0||0||1|。现在,当我试图将变量 x 左移 16 位时,我希望得到输出 0。但令我惊讶的是,我得到了 65536。我肯定错过了一些我无法得到的东西。

这是我的代码:

#include <iostream>

int main() {
    uint8_t x = 1;
    std::cout<<(x<<16)<<"\n";
    return 0;
}

这个问题很幼稚,但让我很困扰。

在这个表达式中

x<<16

整数提升应用于两个操作数。所以表达式的结果是一个int类型的对象。

试试下面的演示程序

#include <iostream>
#include <iomanip>
#include <type_traits>
#include <cstdint>


int main() 
{
    uint8_t x = 1;

    std::cout << std::boolalpha << std::is_same<int, decltype( x<<16 )>::value << '\b';

    return 0;
}

它的输出是

true

来自 C++ 标准(8.8 移位运算符)

  1. ... The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand.