diff --git a/src/common/bit_util.h b/src/common/bit_util.h index eae8748c..e7ec95b1 100644 --- a/src/common/bit_util.h +++ b/src/common/bit_util.h @@ -59,7 +59,7 @@ constexpr bool Bit(size_t bit_position, const T value) { #pragma warning(pop) #endif -/// Sign-extends a value that has NBits bits to the full bitwidth of type T. +/// Sign-extends a value that has bit_count bits to the full bitwidth of type T. template inline T SignExtend(const T value) { static_assert(bit_count <= BitSize(), "bit_count larger than bitsize of T"); @@ -72,6 +72,19 @@ inline T SignExtend(const T value) { return value; } +/// Sign-extends a value that has bit_count bits to the full bitwidth of type T. +template +inline T SignExtend(const size_t bit_count, const T value) { + ASSERT_MSG(bit_count <= BitSize(), "bit_count larger than bitsize of T"); + + const T mask = static_cast(1ULL << bit_count) - 1; + const bool signbit = Bit(bit_count - 1, value); + if (signbit) { + return value | ~mask; + } + return value; +} + template inline size_t BitCount(Integral value) { return std::bitset()>(value).count();