Bitwise operations

13.2 - Bit shift operators


The bit shift operations work by shifting the bits of a value. The operators are << for left shift and >> for right shift.

These operators take two numbers. The left operand will be shifted by the right operand.

Examples

unsigned int n = 42; // 101010
unsigned int m = n << 2; // 168 or 10101000
unsigned int l = n >> 3; // 5 or 101

Task

Make a program which prints the power of twos starting from 1 (20) to 2147483648 (231).

  • Create a for loop with int i going from 0 to 31.
  • Print out 1ul shifted to the left by i:
    • The number one must be 1ul so it is an unsigned long.
    • Wrap the shift expression inside a parentheses to make the std::cout << operator run after the shift.
    • The line should look like: std::cout << (1ul << i) << '\n'.