hmbdc
simplify-high-performance-messaging-programming
BitMath.hpp
1 #include "hmbdc/Copyright.hpp"
2 #pragma once
3 #include <stdint.h>
4 #include <type_traits>
5 
6 namespace hmbdc { namespace numeric {
7 
8 template <uint64_t v>
9 struct set_bits_count {
10  enum {
11  value = set_bits_count<v/2u>::value + v % 2u
12  };
13 };
14 
15 template <>
16 struct set_bits_count<0> {
17  enum {
18  value = 0
19  };
20 };
21 
22 
23 template <typename U>
24 uint16_t setBitsCount(U x) {
25  static_assert(std::is_unsigned<U>::value, "");
26  uint16_t c = 0;
27  for (c = 0; x; c++, x &= x-1);
28  return c;
29 }
30 
31 template <typename U>
32 U nthSetBitFromLsb(U x, uint16_t n) {
33  static_assert(std::is_unsigned<U>::value, "");
34  U res;
35  do {
36  res = x - (x & (x - 1));
37  x -= res;
38  } while (n--);
39  return res;
40 }
41 
42 
43 template <typename U>
44 uint16_t log2Upper(U x) {
45  static_assert(std::is_unsigned<U>::value, "");
46  uint16_t l = 0u;
47  auto xx = x;
48  while (xx >>= 1u) { ++l; }
49  return (1ul << l) == x ? l : ++l;
50 }
51 
52 template <typename U, typename Indexes>
53 U fromSetBitIndexes(Indexes const& indexes) {
54  U res{0};
55  for (auto i : indexes) {
56  res |= (1u << i);
57  }
58  return res;
59 }
60 }}
61 
Definition: BitMath.hpp:9
Definition: Base.hpp:12