C/C++ Arena

Step 3 of 5

Bitwise operators

Bitwise operators work on the individual bits of integers:

Op Name Example (binary)
& AND 1100 & 1010 = 1000
| OR 1100 | 1010 = 1110
^ XOR 1100 ^ 1010 = 0110
~ NOT flips every bit
<< shift left 0001 << 2 = 0100
>> shift right 1000 >> 3 = 0001

1 << n is a number with only bit n set (that's 2 to the power n).

Your turn: write int count_bits(unsigned x) that returns how many bits are 1. Check the lowest bit with x & 1, then shift right.

Previous: Macro pitfalls Next: Flags