Write a C program to count bits set in an integer?

Method1

This is the most basic way of doing it.

#include<stdio.h>
int main()
{
unsinged int num=10;
int ctr=0;

for(;num!=0;num>>=1)
{
if(num&1)
{
ctr++;
}
}

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

}

Method2

This is a faster way of doing the same thing. Here the control goes into the while loop only as many times as the number of bits set to 1 in the integer!.

#include<stdio.h>
int main()
{
int num=10;
int ctr=0;

while(num)
{
ctr++;
num = num & (num – 1); // This clears the least significant bit set.
}

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

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s