Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 932
rlbond Avatar asked Mar 30 '09 16:03

rlbond


People also ask

How many bits is a unsigned char?

The smallest group of bits the language allows use to work with is the unsigned char , which is a group of 8 bits.


2 Answers

const unsigned char oneBits[] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};

unsigned char CountOnes(unsigned char x)
{
    unsigned char results;
    results = oneBits[x&0x0f];
    results += oneBits[x>>4];
    return results
}

Have an array that knows the number of bits for 0 through 15. Add the results for each nibble.

like image 166
Robert Avatar answered Oct 22 '22 00:10

Robert


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

like image 30
dirkgently Avatar answered Oct 22 '22 00:10

dirkgently