Count number of bits in a number source code

This snippet submitted by Naren Bala on 2005-09-26. It has been viewed 3485 times.
Rating of 5.1 with 9 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

Add a snippet!