9#ifndef FORTRAN_COMMON_BIT_POPULATION_COUNT_H_
10#define FORTRAN_COMMON_BIT_POPULATION_COUNT_H_
22template <
typename INT,
23 std::enable_if_t<(
sizeof(INT) > 4 &&
sizeof(INT) <= 8),
int> = 0>
24inline constexpr int BitPopulationCount(INT x) {
27 x = (x & 0x5555555555555555) + ((x >> 1) & 0x5555555555555555);
29 x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
31 x = (x & 0x0f0f0f0f0f0f0f0f) + ((x >> 4) & 0x0f0f0f0f0f0f0f0f);
33 x = (x & 0x001f001f001f001f) + ((x >> 8) & 0x001f001f001f001f);
35 x = (x & 0x0000003f0000003f) + ((x >> 16) & 0x0000003f0000003f);
37 return (x & 0x7f) + (x >> 32);
40template <
typename INT,
41 std::enable_if_t<(
sizeof(INT) > 2 &&
sizeof(INT) <= 4),
int> = 0>
42inline constexpr int BitPopulationCount(INT x) {
45 x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
47 x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
49 x = (x & 0x0f0f0f0f) + ((x >> 4) & 0x0f0f0f0f);
51 x = (x & 0x001f001f) + ((x >> 8) & 0x001f001f);
53 return (x & 0x3f) + (x >> 16);
56template <
typename INT, std::enable_if_t<sizeof(INT) == 2,
int> = 0>
57inline constexpr int BitPopulationCount(INT x) {
60 x = (x & 0x5555) + ((x >> 1) & 0x5555);
62 x = (x & 0x3333) + ((x >> 2) & 0x3333);
64 x = (x & 0x0f0f) + ((x >> 4) & 0x0f0f);
66 return (x & 0x1f) + (x >> 8);
69template <
typename INT, std::enable_if_t<sizeof(INT) == 1,
int> = 0>
70inline constexpr int BitPopulationCount(INT x) {
73 x = (x & 0x55) + ((x >> 1) & 0x55);
75 x = (x & 0x33) + ((x >> 2) & 0x33);
77 return (x & 0xf) + (x >> 4);
80template <
typename INT>
inline constexpr bool Parity(INT x) {
81 return BitPopulationCount(x) & 1;
86template <
typename INT>
inline constexpr int TrailingZeroBitCount(INT x) {
90 return CHAR_BIT *
sizeof x;
92 return BitPopulationCount(
static_cast<INT
>(x ^ (x - 1))) - 1;
Definition: bit-population-count.h:20