Search code examples
c++bit-manipulationbitset

c++ printing out incorrect binary after shifting << 32 times


The code below should be printing out 32 0s, then 011, then 0s till the 64 bit from right to left

#include <iostream>
#include <bitset>
#include <stdint.h>
using namespace std;

int main() {
  int a = 0b011;
  long long b = (a << 32);


  std::cout << bitset<64>(b).to_string();
}

but its giving this:

main.cpp:8:20: warning: shift count >= width of type [-Wshift-count-overflow]
  long long b = (a << 32);
                   ^  ~~
1 warning generated.

And the incorrect input is this:

0000000000000000000000000000000000000000010000000000101011110000

Solution

  • It seems the shifting is done in 32-bit because both of a and 32 are 32-bit long.

    Cast to long long before shifting to fix.

    long long b = ((long long)a << 32);