223. count_ones — Count Set Bits Without a Loop
Need to count how many bits are set in an integer — flags in a bitmask, a population count, a Hamming weight? Don’t write a shift-and-mask loop. Every integer type has .count_ones(), and it usually lowers to a single CPU instruction.
The hand-rolled version is a loop that masks the low bit and shifts:
| |
It works, but it’s a loop you have to get right, and it’s slower than the hardware can do the same job.
Enter count_ones
| |
One call. It’s available on every integer type (u8..u128, i8..i128), and on most targets it compiles straight to a popcnt instruction.
Where it earns its keep
Hamming distance — XOR two values, then count the bits that differ:
| |
Power-of-two test — a power of two has exactly one bit set:
| |
The rest of the family
count_zeros, leading_zeros, trailing_zeros, leading_ones, and trailing_ones round it out — all single-instruction on modern CPUs. leading_zeros is the trick behind a fast integer log2; trailing_zeros gives you the index of the lowest set bit:
| |
Next time you reach for a bit-counting loop, reach for count_ones instead. Stable since Rust 1.0.