calculate number of bits set in byte

前端 未结 11 2179
抹茶落季
抹茶落季 2020-12-09 18:58

I am interested, which is the optimal way of calculating the number of bits set in byte by this way

template< unsigned char byte > class BITS_SET
{
pub         


        
11条回答
  •  一生所求
    2020-12-09 19:33

    For one byte of data, the optimal way considering both speed and memory consumption:

    uint8_t count_ones (uint8_t byte)
    {
      static const uint8_t NIBBLE_LOOKUP [16] =
      {
        0, 1, 1, 2, 1, 2, 2, 3, 
        1, 2, 2, 3, 2, 3, 3, 4
      };
    
    
      return NIBBLE_LOOKUP[byte & 0x0F] + NIBBLE_LOOKUP[byte >> 4];
    }
    

    Calling this function from a for loop should yield quite an efficient program on most systems. And it is very generic.

提交回复
热议问题