Skip to content
BytePatterns

Counting Set Bits

Bit Manipulation: lesson 3 of 5

Clear the lowest 1 and count how often you can.

Lesson 3 of 5 · 4 min

Counting Set Bits

Step 1 of 8

44 has three 1s among eight lanes. Checking every lane would visit five zeros for nothing.

The Idea

Subtracting 1 from a number flips its lowest 1 to 0 and turns every 0 below it into 1. AND the two values together and that tail is wiped out — one set bit gone, the rest untouched.

Repeat until nothing is left. The loop runs once per 1, not once per bit.

Real-World Example

Bloom filters and database bitmap indexes report "how many rows matched?" by popcounting a bitmap. The count must be cheap because it runs over megabytes of bitmap per query — walking all 64 lanes of every word would be wasted work on sparse data.

The Code

def popcount(x):
    count = 0
    while x:
        x &= x - 1          # wipes the lowest set bit, nothing else
        count += 1
    return count            # one pass per 1, not per bit

print(popcount(44))         # 3   -> 0b101100 has three 1s
print(popcount(255))        # 8
print(bin(44), bin(43))     # 0b101100 0b101011 -> the tail flipped
print(bin(44 & 43))         # 0b101000 -> lowest 1 cleared

Python

Your turn

Put the steps in the right order.

  1. Subtract 1, flipping the lowest 1 and every 0 below it
  2. Start with count = 0
  3. AND the two values to wipe that lowest 1
  4. Add one to the count, and repeat while x is non-zero

Mini quiz

1 / 3

How many iterations does the loop run for a value with k set bits?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.