Thursday, July 9, 2015

Count the number of bits in an integer


Question
Why would someone count the number of bits in an integer ?
To Calculate parity (Okay you need to track whether the number of bits is odd or even)

Solution

    int countBits(uint32_t n) {
        int count = 0;
        while (n > 0)
        {
            n = n&(n-1);
            count++;
        }
       
        return count;
}


Trick
The expression n&(n-1) indicates whether n is a power of 2

No comments:

Post a Comment