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<std::uint8_t
>((x + (x >> 4)) & 0x0F);
40 x = x - ((x >> 1) & 0x5555);
41 x = (x & 0x3333) + ((x >> 2) & 0x3333);
42 return static_cast<std::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__)
65static inline unsigned popcount(
unsigned i) {
66 return static_cast<unsigned>(__builtin_popcount(i));
70static inline unsigned popcount(
int i) {
71 return popcount(
static_cast<unsigned>(i));
75static inline unsigned popcount(
unsigned long i) {
76 return static_cast<unsigned>(__builtin_popcountl(i));
80static inline unsigned popcount(
long i) {
81 return popcount(
static_cast<unsigned long>(i));
85static inline unsigned popcount(
unsigned long long i) {
86 return static_cast<unsigned>(__builtin_popcountll(i));
90static inline unsigned popcount(
long long i) {
91 return popcount(
static_cast<unsigned long long>(i));
94#elif defined(_MSC_VER)
97template <
typename Integral>
98inline unsigned popcount(Integral i) {
99 if (
sizeof(i) <=
sizeof(
int))
103 return __popcnt64(i);
113template <
typename Integral>
115 if (
sizeof(i) <=
sizeof(std::uint8_t))
117 else if (
sizeof(i) <=
sizeof(std::uint16_t))
119 else if (
sizeof(i) <=
sizeof(std::uint32_t))
121 else if (
sizeof(i) <=
sizeof(std::uint64_t))
134 const std::uint8_t* begin =
reinterpret_cast<const std::uint8_t*
>(data);
135 const std::uint8_t* end = begin + size;
137 while (begin + 7 < end) {
138 total +=
popcount(*
reinterpret_cast<const std::uint64_t*
>(begin));
141 if (begin + 3 < end) {
142 total +=
popcount(*
reinterpret_cast<const std::uint32_t*
>(begin));
145 while (begin < end) {
static unsigned popcount_generic32(std::uint32_t x)
popcount (count one bits) - generic SWAR implementation from https://stackoverflow....
static unsigned popcount_generic16(std::uint16_t x)
popcount (count one bits) - generic SWAR implementation
static unsigned popcount_generic64(std::uint64_t x)
popcount (count one bits) - generic SWAR implementation
static unsigned popcount_generic8(std::uint8_t x)
popcount (count one bits) - generic SWAR implementation
unsigned popcount(Integral i)
popcount (count one bits)