Count number of bits in a number source code

This snippet submitted by Naren Bala on 2005-09-26. It has been viewed 10383 times.
Rating of 5.9 with 60 votes

 
 // portable code to count the number of bits
#include <stdio.h>

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

 




More C and C++ source code snippets