Bit.h
Go to the documentation of this file.
1 #ifndef _utl_Bit_h_
2 #define _utl_Bit_h_
3 
12 #include <utl/AugerException.h>
13 
14 
15 namespace utl {
16 
17  namespace Bit {
18 
19  template<typename T>
20  class Array {
21  public:
22  Array(T& target) : fTarget(target) { }
23 
24  class Bit {
25  public:
26  Bit(T& target, T mask) : fTarget(target), fMask(mask) { }
27 
28  operator bool() const { return fTarget & fMask; }
29 
30  bool operator~() const { return !bool(*this); }
31 
32  Bit&
33  operator=(const bool value)
34  {
35  if (value)
36  fTarget |= fMask;
37  else
38  fTarget &= ~fMask;
39  return *this;
40  }
41 
42  Bit& Flip() { return *this = ~(*this); }
43 
44  private:
45  T& fTarget;
46  T fMask;
47  };
48 
49  Bit operator[](const unsigned int position)
50  { return Bit(fTarget, T(1) << position); }
51 
52  Bit
53  At(const unsigned int position)
54  {
55  if (position >= 8*sizeof(T))
56  throw OutOfBoundException("Running out of bits.");
57  return (*this)[position];
58  }
59 
60  template<typename M>
61  Array& Mask(const M mask, const bool value)
62  { Bit(fTarget, mask) = value; return *this; }
63 
64  template<typename M>
65  T Get(const M mask) { return fTarget & T(mask); }
66 
67  private:
68  T& fTarget;
69  };
70 
71  }
72 
73  // helper
74  template<typename T>
75  inline
77  AsBitArray(T& target)
78  {
79  return Bit::Array<T>(target);
80  }
81 
82 }
83 
84 
85 #endif
Bit::Array< T > AsBitArray(T &target)
Definition: Bit.h:77
T & fTarget
Definition: Bit.h:68
Bit At(const unsigned int position)
Definition: Bit.h:53
Exception for reporting variable out of valid range.
Array(T &target)
Definition: Bit.h:22
Bit & Flip()
Definition: Bit.h:42
Array & Mask(const M mask, const bool value)
Definition: Bit.h:61
bool operator~() const
Definition: Bit.h:30
Bit & operator=(const bool value)
Definition: Bit.h:33
Bit operator[](const unsigned int position)
Definition: Bit.h:49
Bit(T &target, T mask)
Definition: Bit.h:26
T Get(const M mask)
Definition: Bit.h:65

, generated on Tue Sep 26 2023.