Q40 Write a C program to count number of bits set in an integer.

The simplest way is, use bitwise ‘&’ operator on each bit of number by shifting right one by one and whenever found a bit is set then increment count by one.

int main()

{

unsinged int num = 10;

int count = 0;

for(; num!= 0; num >>= 1)

{

if(num & 1)

{

     count++;

}

}

printf(“\n Number of bits set in [%d] = [%d]\n”, num, count);

return(0);

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.