Jun 30, 2012

Searching for a position of set bits in a variable

In a deamon that I have created in Badoo I need to search for a positions of a bits in a 32 bit variable. The simplest solution is to look at each bit, but there is a faster solution using GCC built in function __builtin_ctzl:
Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.
So I wrote test to compare speed of these two approaches:

Here is the result of testing on my VirtualBox:

While writing test, I have stumbled upon issue with bit shifting. It happened that if you right shift by the size of a variable, you get not 0, but same number. So I have additional if statement for case when I have to shift by 32.