Skip to content

Instantly share code, notes, and snippets.

@roehrdor
Created September 24, 2018 07:31
Show Gist options
  • Save roehrdor/6925f0143ae7e54d7c7e31c5bc859f84 to your computer and use it in GitHub Desktop.
Save roehrdor/6925f0143ae7e54d7c7e31c5bc859f84 to your computer and use it in GitHub Desktop.
BitField Class Wrapper
#include <cstdint>
#include <cstdlib>
template <class T = uint_least64_t, size_t size = 64, T first = 0, T last = first>
constexpr T genMask() {
static_assert(first <= last, "");
static_assert(first < size && last < size, "");
return (1ULL << last) | ((1ULL << (last - first)) - 1ULL) << first;
}
template <class T = uint_least64_t, T first = 0, T last = first>
class BitField {
T mask {genMask<T, sizeof(T) * 8, first, last>()};
T negMask {~mask};
T& value;
public:
constexpr BitField(T& value) noexcept : value(value) {}
constexpr operator T() const noexcept {
return (this->value & mask) >> first;
}
BitField& operator = (T value) noexcept {
this->value &= negMask | ((value << first) & mask);
return *this;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment