最近做项目的时候发现需要对unsigner integer类型的数据进行大量位操作;
限于STL <bit> 中提供的操作严重不足,便随手写了一个扩展库来满足自己的需要;
如果需要,欢迎复制粘贴 - 只要能帮助到大家就好 (*^▽^*)!
PS:如果有对C++语言感兴趣的小伙伴欢迎关注我的频道ya!最近准备写一些关于C++的博客,能与大家一起讨论真的很开心。
代码如下:
export module freefunc;
#include <concepts>
#include <optional>
namespace freefunc {
// one can simply use <bit> stl.
// here implement some necessary operations that <bit> does not have
// define bit size of a byte
export constexpr std::uint32_t byte_size = 8;
// bit in range: test if the given bit position is within the range
// NOTE: POS is the index of the bit, from 0, start from right (least significant)
export template <typename Int> requires std::integral<Int>
[[nodiscard]] constexpr auto bit_inrange(const std::size_t pos) noexcept -> bool {
return pos >= 0 && pos < sizeof(Int) * byte_size;
}
// bit test: test if a bit is set to true
// NOTE: POS is the index of the bit, from 0, start from right (least significant)
export template <typename Int> requires std::integral<Int>
[[nodiscard]] constexpr auto bit_test(Int n, std::size_t pos) noexcept -> bool {
if (!bit_inrange<Int>(pos)) {
return false;
}
// 1 << pos ==> 0b0000 0001 -> 0b0010 0000
// n & (1 << pos) ==> 0b0101 1101 & 0b0010 0000 -> 0b0000 0000 -> false
return n & (static_cast<std::uintmax_t>(1) << pos);
}
// bit_test_all: test if all the bit is set to true
// NOTE: last_nbit is the number of bits to be tested, start from right (least significant)
// overload 1: entire range
export template <typename Int> requires std::integral<Int>
[[nodiscard]] constexpr auto bit_test_all(Int n) noexcept -> bool {
std::size_t last_nbit{ sizeof(Int) * byte_size - 1 };
bool res{ true };
// prevent from overflow
if (sizeof(Int) == sizeof(std::uintmax_t)) {
res &= bit_test<Int>(n, last_nbit); // check the highest bit
n >>= 1; // move the bits down by 1
--last_nbit; // dec the check range
}
const Int mask{ (static_cast<std::uintmax_t>(1) << (last_nbit + 1)) - 1 };
n &= mask;
return n == mask && res;
}
// overload 2: user provided range
export template <typename Int> requires std::integral<Int>
[[nodiscard]] constexpr auto bit_test_all(Int n, std::size

本文提供了一组C++模板函数,用于扩展STL中位操作的功能,包括检查位范围、测试位、全位测试、任意位测试、无位测试、设置位、重置位和翻转位。同时,文章包含单元测试以验证函数的正确性。
最低0.47元/天 解锁文章
5836

被折叠的 条评论
为什么被折叠?



