Search code examples
chammingweight

C code to count the number of '1' bits in an unsigned char


I need C code to return the number of 1's in an unsigned char in C. I need an explanation as to why it works if it's not obvious. I've found a lot of code for a 32-bit number but not much for an unsigned char.


Solution

  • The same code will work for an unsigned char. Loop over all bits testing them. See this.