commonlib
bithelper.h
Go to the documentation of this file.
1 
11 #pragma once
12 
13 #include "datatypes.h"
14 #include <climits>
15 #include <limits>
16 #include <type_traits>
17 
18 BEGIN_NAMESPACE_DATATYPES
19 
23 class BitHelper
24 {
25 public:
26  template <typename T = uint32_t, typename UT = typename std::make_unsigned<T>::type>
27  constexpr static UT lsbMask(int N);
28 
29  template <typename T = uint32_t, typename UT = typename std::make_unsigned<T>::type>
30  constexpr static UT lsbInvMask(int N);
31 
32  template <typename T = uint32_t, typename UT = typename std::make_unsigned<T>::type>
33  constexpr static UT msbMask(int N);
34 
35  template <typename T = uint32_t, typename UT = typename std::make_unsigned<T>::type>
36  constexpr static UT msbInvMask(int N);
37 
38  template <typename T>
39  constexpr static T reverseBitOrder(T N);
40 };
41 
42 template <typename T, typename UT>
43 constexpr UT BitHelper::lsbMask(int N)
44 {
45  using SignedSize = std::make_signed_t<std::size_t>;
46 
47  if (((SignedSize) sizeof(UT) * 8) <= N)
48  return (std::numeric_limits<UT>::max)();
49 
50  return UT(~((std::numeric_limits<UT>::max)() << N));
51 }
52 
53 template <typename T, typename UT>
54 constexpr UT BitHelper::lsbInvMask(int N)
55 {
56  return ~lsbMask<T, UT>(N);
57 }
58 
59 template <typename T, typename UT>
60 constexpr UT BitHelper::msbMask(int N)
61 {
62  using SignedSize = std::make_signed_t<std::size_t>;
63 
64  if (((SignedSize) sizeof(UT) * 8) <= N)
65  return (std::numeric_limits<UT>::max)();
66 
67  return UT(~((std::numeric_limits<UT>::max)() >> N));
68 }
69 
70 template <typename T, typename UT>
71 constexpr UT BitHelper::msbInvMask(int N)
72 {
73  return ~msbMask<T, UT>(N);
74 }
75 
76 template <typename T>
77 constexpr T BitHelper::reverseBitOrder(T N)
78 {
79  T reverseValue = 0;
80  int numberOfBits = sizeof(N) * CHAR_BIT;
81  for (int i = 0; i < numberOfBits; i++)
82  {
83  reverseValue = (reverseValue << 1) | (N & 1);
84  N >>= 1;
85  }
86  return reverseValue;
87 }
88 
89 END_NAMESPACE_DATATYPES
The class BitHelper implements functions for handling bits.
Definition: bithelper.h:23