Math Fundamentals18 sections · 814 units
Open in Course

Count Bits - Checking Each Bit

Shift and mask

One way to count 1 bits: check each of the 32 bits individually. Use a mask (a number with one bit set) and the AND operation to test if that bit is 1.

The AND operation (&\&) returns 1 only when both bits are 1. So n&1n \& 1 checks the rightmost bit. If the result is nonzero, that bit is 1. Then shift nn right by 1 to check the next bit.

Repeat 32 times (for a 32-bit integer). Each iteration checks one bit and shifts. This works but is not the fastest method. There is a clever trick that processes only the 1 bits.