Left shift operation on an unsigned 8 bit integer [duplicate]

ε祈祈猫儿з 提交于 2021-01-27 17:10:50

问题


I am trying to understand shift operators in C/C++, but they are giving me a tough time.

I have an unsigned 8-bit integer initialized to a value, for the example, say 1.

uint8_t x = 1;

From my understanding, it is represented in the memory like |0|0|0|0|0||0||0||1|. Now, when I am trying to left shit the variable x by 16 bit, I am hoping to get output 0. But to my surprise, I am getting 65536. I am certainly missing something which I am not able to get.

Here's my code:

#include <iostream>

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

It's a naive question, but it is bothering me a lot.


回答1:


In this expression

x<<16

the integer promotions are applied to the both operands. So the result of the expression is an object of the type int.

Try the following demonstrative program

#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;
}

Its ouput is

true

From the C++ Standard (8.8 Shift operators)

  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.


来源:https://stackoverflow.com/questions/60117496/left-shift-operation-on-an-unsigned-8-bit-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!