How to implement Bitcount using only Bitwise operators?

后端 未结 4 1127
一生所求
一生所求 2020-11-29 02:14

The task is to implement a bit count logic using only bitwise operators. I got it working fine, but am wondering if someone can suggest a more elegant approach.

Onl

4条回答
  •  爱一瞬间的悲伤
    2020-11-29 03:20

    I would use a pre-computed array

    uint8_t set_bits_in_byte_table[ 256 ];
    

    The i-th entry in this table stores the number of set bits in byte i, e.g. set_bits_in_byte_table[ 100 ] = 3 since there are 3 1 bits in binary representation of decimal 100 (=0x64 = 0110-0100).

    Then I would try

    size_t count_set_bits( uint32_t const x ) {
        size_t count = 0;
        uint8_t const * byte_ptr = (uint8_t const *) &x;
        count += set_bits_in_byte_table[ *byte_ptr++ ];
        count += set_bits_in_byte_table[ *byte_ptr++ ];
        count += set_bits_in_byte_table[ *byte_ptr++ ];
        count += set_bits_in_byte_table[ *byte_ptr++ ];
        return count;
    }
    

提交回复
热议问题