calculate number of bits set in byte

前端 未结 11 2053
抹茶落季
抹茶落季 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:31

    Using C++17 you can precalculate the lookup table using a constexpr lambda. Easier to reason about the correctness of it rather than a ready copy-pasted table.

    #include 
    
    static constexpr auto bitsPerByteTable = [] {
      std::array table{};
      for (decltype(table)::size_type i = 0; i < table.size(); i++) {
        table.at(i) = table.at(i / 2) + (i & 1);
      }
      return table;
    }();
    

提交回复
热议问题