Bit Counting

The methods identified as fast are from Hacker's Delight. Henry Warren clearly intends the original, respectable meaning of hacker, rather than today's popular usage of the term.

Apart from providing interactive demonstrations, and making a few cosmetic changes, I've added social commentary that hopefully explains rather than distracts. Invariants unmentioned by Hacker's Delight are explicitly specified. Vanilla alternative methods, identified as simple, are provided for comparison purposes. Their worst case performance is far inferior to the fast methods.

I ran some speed tests to compare performance of the fast and simple implementations. The code was run directly on the Silverlight CLR, rather than using my interpreter, which is embedded in this web page. Your mileage may vary.

CountOnesFast is eight times the speed of CountOnesSimple. There are no performance tradeoffs.

NumberLeadingZerosFast is about ten percent faster than NumberLeadingZerosSimple on random data. The simple method wins by fifteen percent on input with no zeros. Both methods are the same speed when the the input is zero. In all other cases, the fast method outperforms the simple implementation. The speed advantage increases with the number of leading zeros. Fast beats simple by more than a factor of two on input with eight leading zeros, and wins by a factor of four with thirty leading zeros.

NumberTrailingZerosFast is about twenty five percent faster than NumberTrailingZerosSimple on random data, and is ten percent slower when there are no trailing zeros. Both methods are the same speed when the input is zero, or has exactly one trailing zero. In all other cases, the fast method beats the simpler one. The disparity increases with the number of trailing zeros, with fast beating simple by a factor of two on input with eight trailing zeros, and winning by a factor of eight when there are thirty. I was surprised to discover that the simple implementation slightly outperforms the code shown on page 86 of Hacker's Delight across the board.

Hacker's Delight provides multiple alternatives to the methods demonstrated here, with a variety of performance advantages and disadvantages. It also contains nice solutions to a large variety of other problems.

Some readers may wonder whether such code is relevant to modern software. Most programmers no longer need such elaborate bit twiddling, but some do. Anyway it's good entertainment, and that's the purpose of this website. Of course you may disagree with my notion of entertainment, but that's a different story.

Valid CSS 2.1!