C Program – Count number of 1 bits in an Integer


To Count the number of 1 bits contained within an unsigned integer

/* Count the number of 1 bits contained within an unsigned integer */
#include <stdio.h>

int main()
{
    unsigned int num = 255; /* to find the number of 1 bits in this number */
    unsigned int orgvalue = num;
    int count;

    for (count = 0; num != 0; count++)
        num = num & (num - 1);

    printf("The no. of  bits in %d is %d\n", orgvalue, count);
    /* getch(); */
}

%d bloggers like this: