13 #ifndef TLX_MATH_POPCOUNT_HEADER 14 #define TLX_MATH_POPCOUNT_HEADER 33 x = x - ((x >> 1) & 0x55);
34 x = (x & 0x33) + ((x >> 2) & 0x33);
35 return static_cast<uint8_t
>((x + (x >> 4)) & 0x0F);
40 x = x - ((x >> 1) & 0x5555);
41 x = (x & 0x3333) + ((x >> 2) & 0x3333);
42 return static_cast<uint16_t
>(((x + (x >> 4)) & 0x0F0F) * 0x0101) >> 8;
48 x = x - ((x >> 1) & 0x55555555);
49 x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
50 return (((x + (x >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
55 x = x - ((x >> 1) & 0x5555555555555555);
56 x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
57 return (((x + (x >> 4)) & 0x0F0F0F0F0F0F0F0F) * 0x0101010101010101) >> 56;
62 #if defined(__GNUC__) || defined(__clang__) 65 static inline unsigned popcount(
unsigned i) {
66 return static_cast<unsigned>(__builtin_popcount(i));
70 static inline unsigned popcount(
int i) {
71 return popcount(static_cast<unsigned>(i));
75 static inline unsigned popcount(
unsigned long i) {
76 return static_cast<unsigned>(__builtin_popcountl(i));
80 static inline unsigned popcount(
long i) {
81 return popcount(static_cast<unsigned long>(i));
85 static inline unsigned popcount(
unsigned long long i) {
86 return static_cast<unsigned>(__builtin_popcountll(i));
90 static inline unsigned popcount(
long long i) {
91 return popcount(static_cast<unsigned long long>(i));
94 #elif defined(_MSC_VER) 97 template <
typename Integral>
98 inline unsigned popcount(Integral i) {
99 if (
sizeof(i) <=
sizeof(
int))
103 return __popcnt64(i);
113 template <
typename Integral>
115 if (
sizeof(i) <=
sizeof(uint8_t))
117 else if (
sizeof(i) <=
sizeof(uint16_t))
119 else if (
sizeof(i) <=
sizeof(uint32_t))
121 else if (
sizeof(i) <=
sizeof(uint64_t))
134 const uint8_t* begin =
reinterpret_cast<const uint8_t*
>(data);
135 const uint8_t* end = begin + size;
137 while (begin + 7 < end) {
138 total +=
popcount(*reinterpret_cast<const uint64_t*>(begin));
141 if (begin + 3 < end) {
142 total +=
popcount(*reinterpret_cast<const uint32_t*>(begin));
145 while (begin < end) {
155 #endif // !TLX_MATH_POPCOUNT_HEADER static unsigned popcount_generic64(uint64_t x)
popcount (count one bits) - generic SWAR implementation
static unsigned popcount_generic8(uint8_t x)
popcount (count one bits) - generic SWAR implementation
unsigned popcount(Integral i)
popcount (count one bits)
static unsigned popcount_generic16(uint16_t x)
popcount (count one bits) - generic SWAR implementation
static unsigned popcount_generic32(uint32_t x)