int x = 5; int y = x << 1; int z = x * 2; std::cout << y << " " << z << std::endl;
Left shifting 5 by 1 bit moves its binary digits left, doubling its value to 10. Multiplying 5 by 2 also results in 10. Both print 10.
Bit manipulation often uses simpler CPU instructions that execute faster than arithmetic operations like multiplication or division, which involve more complex logic.
unsigned int num = 29; // binary 11101 unsigned int mask = 14; // binary 01110 unsigned int result = num & mask; std::cout << result << std::endl;
29 in binary is 11101, 14 is 01110. AND operation results in 01100 which is 12 in decimal.
Bit manipulation is fastest when multiplying or dividing by powers of two because shifting bits left or right is simpler than arithmetic multiplication or division.
int x = -4; unsigned int y = x >> 1; std::cout << y << std::endl;
Right shifting a negative signed int assigned to unsigned int causes bit pattern reinterpretation, resulting in a large positive number.
