How to Count Number of 1's in Given Number in C

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>

//Count number of one in given number

int fun_bitCount(int num)
{
char bitCount = 0;
int testBit = 0;
for(int j=1; j<num; j = j << 1)
{
testBit = num & j;
if(testBit)
{
bitCount++;
}
}

return bitCount;
}

int fun_bitCount_lastPos(int num)

{
char bitCount = 0;
int testBit = 0;
while(num > 0)
{
  if(num & 1)
  {
   bitCount++;
  }
  num = num >> 1;
}
return bitCount;
}

int fun_bitCount_firstPos(int num)

{

char bitCount = 0;

int testBit = 0;

while(num != 0)

{
  if(num & 0x8000)
  {
bitCount++;
}
  num = num << 1;
} 
return bitCount;

}


int main()

{

int bitTest = 0x7F00;
printf("bitCount based on bit check = %d\n", fun_bitCount(bitTest));
printf("bitCount based on last bit position = %d\n", fun_bitCount_lastPos(bitTest));
printf("bitCount based on first bit position = %d\n", fun_bitCount_firstPos(bitTest));

getch();
return 0;

}


OUTPUT:

Share on Google Plus

About Kapil Thakar

"I am Kapil Thakar, an Embedded Engineer cum Blogger wants to learn new things. I love to share my knowledge solutions to the problems. Interested in Blogging, Creative-Writing, SEO, Website Creation, Video Making, Editing, Affiliation Programs, Online Making Money."
    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...