Back to TILs

C++ bit shift

Date: 2023-02-20Last modified: 2023-02-21

Table of contents

  unsigned short int value{0b110110};
  auto print = [](auto value) {
    auto ushort =  static_cast<unsigned short int>(value);
    std::cout << "sizeof(value)=" << sizeof(value) << " -> "
              << std::bitset<sizeof(value)*8>(value) << " " << value << "/" << ushort << endl;
  };

  print(value);
  print(value >> 1);
  print(value << 1);
  print(value >> 10);
  print(value << 10);
  print(value << 30);

Possible output

sizeof(value)=2 -> 0000000000110110 54/54
sizeof(value)=4 -> 00000000000000000000000000011011 27/27
sizeof(value)=4 -> 00000000000000000000000001101100 108/108
sizeof(value)=4 -> 00000000000000000000000000000000 0/0
sizeof(value)=4 -> 00000000000000001101100000000000 55296/55296
sizeof(value)=4 -> 10000000000000000000000000000000 -2147483648/0

References