STL <bit> 小型扩展库,有需要请自取!

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

最近做项目的时候发现需要对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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值