Bitmath: Add utility functions for calculating bit masks
Add tests
This commit is contained in:
@@ -187,6 +187,35 @@ inline T ToggleBit(T &x, const uint8_t y)
|
|||||||
return x = (T)(x ^ ((T)1U << y));
|
return x = (T)(x ^ ((T)1U << y));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a bit mask of count bits starting at start.
|
||||||
|
*
|
||||||
|
* @param start The start bit
|
||||||
|
* @param count The number of bits
|
||||||
|
* @pre start + count < sizeof(T) * 8
|
||||||
|
* @return The bit mask
|
||||||
|
*/
|
||||||
|
template <typename T>
|
||||||
|
constexpr T GetBitMaskSC(const uint8_t start, const uint8_t count)
|
||||||
|
{
|
||||||
|
typename std::make_unsigned<T>::type mask = 1;
|
||||||
|
return (T)(((mask << count) - 1) << start);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a bit mask of bits from first to last (inclusive).
|
||||||
|
*
|
||||||
|
* @param first The first bit
|
||||||
|
* @param last The last bits (inclusive)
|
||||||
|
* @pre first <= last && last < sizeof(T) * 8
|
||||||
|
* @return The bit mask
|
||||||
|
*/
|
||||||
|
template <typename T>
|
||||||
|
constexpr T GetBitMaskFL(const uint8_t first, const uint8_t last)
|
||||||
|
{
|
||||||
|
return GetBitMaskSC<T>(first, 1 + last - first);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Search the first set bit in a value.
|
* Search the first set bit in a value.
|
||||||
* When no bit is set, it returns 0.
|
* When no bit is set, it returns 0.
|
||||||
|
@@ -68,3 +68,22 @@ TEST_CASE("SetBitIterator tests")
|
|||||||
CHECK(test_case(INT32_MIN, { 31 }));
|
CHECK(test_case(INT32_MIN, { 31 }));
|
||||||
CHECK(test_case(INT64_MIN, { 63 }));
|
CHECK(test_case(INT64_MIN, { 63 }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST_CASE("GetBitMaskSC tests")
|
||||||
|
{
|
||||||
|
CHECK(GetBitMaskSC<uint>(4, 4) == 0xF0);
|
||||||
|
CHECK(GetBitMaskSC<uint>(28, 4) == 0xF0000000);
|
||||||
|
CHECK(GetBitMaskSC<uint8_t>(7, 1) == 0x80);
|
||||||
|
CHECK(GetBitMaskSC<uint8_t>(0, 1) == 1);
|
||||||
|
CHECK(GetBitMaskSC<uint8_t>(0, 0) == 0);
|
||||||
|
CHECK(GetBitMaskSC<uint8_t>(7, 0) == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("GetBitMaskFL tests")
|
||||||
|
{
|
||||||
|
CHECK(GetBitMaskFL<uint>(4, 7) == 0xF0);
|
||||||
|
CHECK(GetBitMaskFL<uint>(28, 31) == 0xF0000000);
|
||||||
|
CHECK(GetBitMaskFL<uint8_t>(7, 7) == 0x80);
|
||||||
|
CHECK(GetBitMaskFL<uint8_t>(0, 0) == 1);
|
||||||
|
CHECK(GetBitMaskFL<uint8_t>(3, 4) == 0x18);
|
||||||
|
}
|
||||||
|
Reference in New Issue
Block a user