cppx-core
sum_of_bits.hpp
Go to the documentation of this file.
1 #pragma once // Source encoding: UTF-8 with BOM (π is a lowercase Greek "pi").
2 
6 #include <cppx-core/language/syntax/macro-use.hpp> // CPPX_USE_CPPX
7 #include <cppx-core/language/bit-level/bits_per_.hpp> // cppx::bits_per_
8 
9 #include <bitset> // std::bitset
10 #include <type_traits> // std::is_unsigned_v
11 
12 namespace cppx
13 {
14  using std::bitset;
15 
17  template< int n >
18  inline auto sum_of_bits( const bitset<n>& bits ) noexcept
19  -> int
20  { return bits.count(); }
21 
23  template< class Unsigned >
24  inline auto sum_of_bits( const uint16_t x ) noexcept
25  -> int
26  {
27  static_assert( std::is_unsigned_v<Unsigned> );
28  return bitset<bits_per_<Unsigned>>( x ).count();
29  }
30 
31 #if 0 // Possible optimizations, probably not needed
32 #if defined( _MSC_VER )
33 
34  inline auto sum_of_bits( const uint16_t x ) noexcept
35  -> int
36  { return __popcnt16( x ); }
37 
38  inline auto sum_of_bits( const uint32_t x ) noexcept
39  -> int
40  { return __popcnt( x ); }
41 
42  inline auto sum_of_bits( const uint64_t x ) noexcept
43  -> int
44  { return __popcnt64( x ); }
45 
46 #elif defined( __GNUC__ )
47 
49  namespace impl
50  {
51  template< class Unsigned >
52  inline auto gcc_sum_of_bits( const Unsigned x ) noexcept -> int;
53 
54  template<> inline auto gcc_sum_of_bits<unsigned>( const unsigned x ) noexcept
55  -> int
56  { return __builtin_popcount( x ); }
57 
58  template<> inline auto gcc_sum_of_bits<unsigned long>( const unsigned long x ) noexcept
59  -> int
60  { return __builtin_popcountl( x ); }
61 
62  template<> inline auto gcc_sum_of_bits<unsigned long long>( const unsigned long long x ) noexcept
63  -> int
64  { return __builtin_popcountll( x ); }
65  } // namespace impl
67 
68  inline auto sum_of_bits( const uint16_t x ) noexcept
69  -> int
70  { return impl::gcc_sum_of_bits<uint32_t>( x ); }
71 
72  inline auto sum_of_bits( const uint32_t x ) noexcept
73  -> int
74  { return impl::gcc_sum_of_bits( x ); }
75 
76  inline auto sum_of_bits( const uint64_t x ) noexcept
77  -> int
78  { return impl::gcc_sum_of_bits( x ); }
79 #endif
80 #endif // 0
81 
82  namespace bitlevel
83  {
85  } // namespace bitlevel
86 } // namespace cppx
auto sum_of_bits(const bitset< n > &bits) noexcept -> int
The number of 1-bits in a std::bitset.
Definition: sum_of_bits.hpp:18
CPPX_USE_CPPX(bits_per_, magnitude_bits_per_)
bits_per_ and magnitude_bits_per_, plus the for-readability constant bits_per_byte.
Macros for generating more concise and clear using statements, primarily $use_cppx and $use_std,...