From 259c3de4178975791b8d4df66723b1e01cce8c7f Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Sat, 15 Dec 2018 15:36:51 +1100 Subject: [PATCH] bitwise: add 'bitfield' type suitable for unions --- bitwise.hpp | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) 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