Browsed by
Tag: calculating bits in an integer

How to calculate the no of bits in an integer

How to calculate the no of bits in an integer

For calculating number of bits in an integer value we can have many approaches. This is more simple in my opinion. If you know anything much simpler than these algorithm you can very well share the knowledge or idea with me.Ask me if you have any doubts in this.
For calculating the no of bits in an given Integer

#include
int main()
{
int number=42,counter=0;
while(number)
{
counter++;
number = number >> 1;
}
printf(“total bits %d”,counter);
}

For calculating the no of 1 bits in an given Integer

#include
int main()
{
int number=42,counter=0;
while(number)
{
counter++;
number = number & (number – 1);
}
printf(“total bits %d”,counter);
}

For calculating the no of 0 bits in an given Integer

#include
int main()
{
int number=42,counter=0;
while(number)
{
counter++;
number = number & -1 ;
}
printf(“total bits %d”,counter);
}