bitwise: add 'bitfield' type suitable for unions
This commit is contained in:
parent
6bcbaeb98e
commit
259c3de417
31
bitwise.hpp
31
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 <typename ValueT, size_t Offset, size_t Size>
|
||||
std::ostream& operator<< (std::ostream &os, bitfield<ValueT,Offset,Size> const &val)
|
||||
{
|
||||
return os << +ValueT(val);
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
|
Loading…
Reference in New Issue
Block a user