Bitwise operations
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
Make a program which prints the power of twos starting from 1 (20) to 2147483648 (231).
int i
going from 0
to 31
.1ul
shifted to the left by i
:1ul
so it is an unsigned long
.std::cout
<<
operator run after the shift.std::cout << (1ul << i) << '\n'
.