The namespace algo::bit
offers a set of bit manipulation algorithms. They can help when the number of
operations is required to be low or when to avoid importing other libraries so save space.
These functions are constexpr
lambda-functions in a header-file. Using them should allow the compiler
to determine sizes in compile-time.
constexpr auto Sign = [](const auto& x);
Returns 0
if x is positive otherwise -1
.
int sign{algo::bit::Sign(-1)};
constexpr auto IsEven = [](const auto& x);
Returns true
if x
is even, false
if odd.
bool even{algo::bit::IsEven(2)};
constexpr auto SetBit = [](const auto& x, const auto& n, const Bit& b);
Changes x
at bit position n
to either 0
or 1
.
unsigned int num{algo::bit::SetBit(0xFFFFF, 15, algo::bit::Bit::False)}; // == 0xF7FFF
constexpr auto IsBit = [](const auto& x, const auto& n);
Returns true if bit number n
in x
is 1
, otherwise false.
bool is_bit{algo::bit::IsBit(0xAAAA, 11)}; // == true
constexpr auto ToggleBit = [](const auto& x, const auto& n);
Changes a bit at position n
in x
, zero to one or one to zero.
unsigned int{algo::bit::ToggleBit(0xBBBB, 14)}; // == 0xFBBB
constexpr auto IsPow2 = [](const auto& x);
Returns true if x
is a power of two, e.g. is a power of 2.
bool is_pow2{algo::bit::IsPow2(1024)}; // == true
constexpr auto NextPow2 = [](auto x);
Returns the next power of two, e.g. the next power of two of 1025 is 2048.
unsigned int next_pow2{algo::bit::NextPow2(1025)}; // == 2048
constexpr auto CountSetBits = [](auto x);
Returns the number of set bits, the number of 1s, in a (binary) number.
unsigned count{algo::bit::CountSetBits(0xFF)}; // == 8
constexpr auto SwapBits = [](const auto& x);
Changes all the true bits to false, and all false bit to true in the input number x
.
unsigned int swapped{algo::bit::SwapBits(170)}; // == 85