bit_util: Add ClearBit and ModifyBit

This commit is contained in:
MerryMage 2018-06-26 20:50:39 +01:00
parent 8651c2d10e
commit 62b640b2fa

View file

@ -36,14 +36,6 @@ constexpr T Bits(const T value) {
#pragma warning(push) #pragma warning(push)
#pragma warning(disable:4554) #pragma warning(disable:4554)
#endif #endif
/// Extracts a single bit at bit_position from value of type T.
template<size_t bit_position, typename T>
constexpr bool Bit(const T value) {
static_assert(bit_position < BitSize<T>(), "bit_position must be smaller than size of T");
return ((value >> bit_position) & 1) != 0;
}
/// Extracts a single bit at bit_position from value of type T. /// Extracts a single bit at bit_position from value of type T.
template<typename T> template<typename T>
inline bool Bit(size_t bit_position, const T value) { inline bool Bit(size_t bit_position, const T value) {
@ -51,6 +43,46 @@ inline bool Bit(size_t bit_position, const T value) {
return ((value >> bit_position) & 1) != 0; return ((value >> bit_position) & 1) != 0;
} }
/// Extracts a single bit at bit_position from value of type T.
template<size_t bit_position, typename T>
constexpr bool Bit(const T value) {
static_assert(bit_position < BitSize<T>(), "bit_position must be smaller than size of T");
return Bit<T>(bit_position, value);
}
/// Clears a single bit at bit_position from value of type T.
template<typename T>
inline T ClearBit(size_t bit_position, const T value) {
ASSERT_MSG(bit_position < BitSize<T>(), "bit_position must be smaller than size of T");
return value & ~(static_cast<T>(1) << bit_position);
}
/// Clears a single bit at bit_position from value of type T.
template<size_t bit_position, typename T>
constexpr T ClearBit(const T value) {
static_assert(bit_position < BitSize<T>(), "bit_position must be smaller than size of T");
return ClearBit<T>(bit_position, value);
}
/// Modifies a single bit at bit_position from value of type T.
template<typename T>
inline T ModifyBit(size_t bit_position, const T value, bool new_bit) {
ASSERT_MSG(bit_position < BitSize<T>(), "bit_position must be smaller than size of T");
return ClearBit<T>(bit_position, value) | (static_cast<T>(new_bit) << bit_position);
}
/// Modifies a single bit at bit_position from value of type T.
template<size_t bit_position, typename T>
constexpr T ModifyBit(const T value, bool new_bit) {
static_assert(bit_position < BitSize<T>(), "bit_position must be smaller than size of T");
return ModifyBit<T>(bit_position, value, new_bit);
}
#ifdef _MSC_VER #ifdef _MSC_VER
#pragma warning(pop) #pragma warning(pop)
#endif #endif