From 62b640b2fa143c39ce545d56485f22008cab6959 Mon Sep 17 00:00:00 2001 From: MerryMage Date: Tue, 26 Jun 2018 20:50:39 +0100 Subject: [PATCH] bit_util: Add ClearBit and ModifyBit --- src/common/bit_util.h | 48 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/src/common/bit_util.h b/src/common/bit_util.h index 775ccda0..0ed24da5 100644 --- a/src/common/bit_util.h +++ b/src/common/bit_util.h @@ -36,14 +36,6 @@ constexpr T Bits(const T value) { #pragma warning(push) #pragma warning(disable:4554) #endif -/// Extracts a single bit at bit_position from value of type T. -template -constexpr bool Bit(const T value) { - static_assert(bit_position < BitSize(), "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. template 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; } + +/// Extracts a single bit at bit_position from value of type T. +template +constexpr bool Bit(const T value) { + static_assert(bit_position < BitSize(), "bit_position must be smaller than size of T"); + + return Bit(bit_position, value); +} + +/// Clears a single bit at bit_position from value of type T. +template +inline T ClearBit(size_t bit_position, const T value) { + ASSERT_MSG(bit_position < BitSize(), "bit_position must be smaller than size of T"); + + return value & ~(static_cast(1) << bit_position); +} + +/// Clears a single bit at bit_position from value of type T. +template +constexpr T ClearBit(const T value) { + static_assert(bit_position < BitSize(), "bit_position must be smaller than size of T"); + + return ClearBit(bit_position, value); +} + +/// Modifies a single bit at bit_position from value of type T. +template +inline T ModifyBit(size_t bit_position, const T value, bool new_bit) { + ASSERT_MSG(bit_position < BitSize(), "bit_position must be smaller than size of T"); + + return ClearBit(bit_position, value) | (static_cast(new_bit) << bit_position); +} + +/// Modifies a single bit at bit_position from value of type T. +template +constexpr T ModifyBit(const T value, bool new_bit) { + static_assert(bit_position < BitSize(), "bit_position must be smaller than size of T"); + + return ModifyBit(bit_position, value, new_bit); +} #ifdef _MSC_VER #pragma warning(pop) #endif