Search code examples
c++bit-shiftcout

How do I use bitwise shifts with cout?


I'm trying to do something similar to this:

#include <iostream>

int main()
{
    std::cout << 1 << 5 << std::endl;
}

I expect 32 (1 shifted left by 5), but I get 15.

I am trying to use a macro like this:

#define BIT_SHIFT(x,y) x << y
...
cout << BIT_SHIFT(1, 5) << std::endl;

and this happens.

Why? How do I fix this?


Solution

  • Just use parentheses:

    #include <iostream>
    
    int main()
    {
        std::cout << (1 << 5) << std::endl;
    }
    

    std::cout << 1 << 5 means "push to output stream first integer literal 1, followed by integer 5". However, adding parantheses changes the order of evaluation, and 1 << 5 is evaluated first, resulting in std::cout << 32 << std::endl; expression.