Search code examples
c++bit-manipulationbit-shiftinteger-promotion

Left shift operation on an unsigned 8 bit integer


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.


Solution

  • 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.