Nice algorithm to detect the number of set bit in a long number (1 in the code)

inline int count_number_bits_set(long l) {
    unsigned int c;
    for(c=0;l;c++)
        l &= l-1;
    return c;
}

The principle is to get rid of the last 1 from l each time.

Source: [http://en.wikipedia.org/wiki/Brian_Kernighan]



blog comments powered by Disqus

Published

02 February 2013

Tags