diff --git a/bitwise.hpp b/bitwise.hpp index 3b1d098f..4f4de06b 100644 --- a/bitwise.hpp +++ b/bitwise.hpp @@ -126,6 +126,37 @@ namespace cruft { return (val >> lo) & (ones >> (sizeof (ValueT) * 8 - (hi - lo + 1))); } -} + + + template < + typename ValueT, + size_t OffsetV, + size_t SizeV + > + class bitfield { + public: + static_assert (SizeV > 0); + static_assert (OffsetV + SizeV <= sizeof (ValueT) * 8); + + decltype(auto) operator+ () const { return +value; } + + operator auto() const + { + auto const MASK = (1u << SizeV) - 1u; + auto const SHIFT = sizeof (ValueT) * 8 - OffsetV - SizeV; + + return (value >> SHIFT) & MASK; + } + + ValueT value; + }; + + + template + std::ostream& operator<< (std::ostream &os, bitfield const &val) + { + return os << +ValueT(val); + } +}; #endif