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

Pan*_*hra 4 c++ bit-manipulation bit-shift integer-promotion

我试图理解 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;
}
Run Code Online (Sandbox Code Playgroud)

这是一个天真的问题,但却让我很困扰。

Vla*_*cow 6

在这个表达式中

x<<16
Run Code Online (Sandbox Code Playgroud)

整数提升适用于两个操作数。所以表达式的结果是一个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;
}
Run Code Online (Sandbox Code Playgroud)

它的输出是

true
Run Code Online (Sandbox Code Playgroud)

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

  1. ...操作数应为整型或无范围枚举类型,并执行整型提升。结果的类型是提升后的左操作数的类型。