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

前端 未结 8 1712
孤街浪徒
孤街浪徒 2020-12-19 04:24

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 nu

相关标签:
8条回答
  • 2020-12-19 05:10
    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.

    0 讨论(0)
  • 2020-12-19 05:10

    See the bit twiddling hacks page: http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan

    there are many good solutions for this.

    Also, this function in its simplest implementation is fairly trivial. You should take the time to learn how to do this.

    0 讨论(0)
提交回复
热议问题