fork(1) download
  1. #include <cstdio>
  2. #include <array>
  3. #include <cstdint>
  4. #include <utility>
  5. #include <limits>
  6.  
  7. namespace detail {
  8. constexpr std::uint8_t popcnt_8(std::uint8_t number) {
  9. number -= ((number >> 1) & 0x55);
  10. number = (number & 0x33) + ((number >> 2) & 0x33);
  11. return ((number + (number >> 4)) & 0x0F);
  12. }
  13.  
  14. template<std::size_t... Indices>
  15. constexpr std::array<std::uint8_t, sizeof...(Indices)>
  16. make_lookup_impl(std::index_sequence<Indices...>) {
  17. return { popcnt_8(Indices)... };
  18. }
  19. } /* detail */
  20.  
  21. constexpr decltype(auto) make_lookup() {
  22. constexpr std::size_t uint8_max = std::numeric_limits<std::uint8_t>::max();
  23. return detail::make_lookup_impl(std::make_index_sequence<uint8_max + 1>{});
  24. }
  25.  
  26. int main() {
  27. const auto lookup = make_lookup();
  28. const auto test = std::numeric_limits<std::uint64_t>::max();
  29.  
  30. std::size_t popcount = 0;
  31. for(std::size_t i = 0; i < sizeof(test); ++i)
  32. popcount += lookup.at(*(reinterpret_cast<const std::uint8_t*>(&test) + i));
  33.  
  34. printf("-- %d\n", popcount);
  35. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
-- 64