0

Let's suppose I have an unsigned integer number represented in an 8bit variable. I want to write a function that returns the number of bits which are set to 1 inside the variable representation. For example the function should return 1 if the number is 1 and 2 if the number is.. let's say 5. How can I do this? I looked on this website to other questions but didn't find a clear answer for my question, or a similar question.

Thanks in advance.

Update:

#include <stdio.h>
#include <stdlib.h>
int NumberOfSetBits(int i)
{
i = i - ((i >> 1) & 0x55555555);
  i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
 return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}

int main(){
printf("%d\n",NumberOfSetBits(4));
return 0;
}
Jack
  • 11
  • 5

0 Answers0