设置一点
使用按位或运算符 (|
) 设置n
第一点number
to 1
.
// Can be whatever unsigned integer type you want, but
// it's important to use the same type everywhere to avoid
// performance issues caused by mixing integer types.
typedef unsigned long Uint;
// In C++, this can be template.
// In C11, you can make it generic with _Generic, or with macros prior to C11.
inline Uint bit_set(Uint number, Uint n) {
return number | ((Uint)1 << n);
}
请注意,移动超过 a 的宽度是未定义的行为Uint
。这同样适用于所有剩余的示例。
清理一点
使用按位与运算符 (&
)来设置n
第一点number
to 0
.
inline Uint bit_clear(Uint number, Uint n) {
return number & ~((Uint)1 << n);
}
您必须使用按位非运算符 (~
),然后与它。
稍微切换一下
使用按位异或运算符 (^
)来切换n
第一点number
.
inline Uint bit_toggle(Uint number, Uint n) {
return number ^ ((Uint)1 << n);
}
检查一下
你没有要求这个,但我不妨添加它。
要检查一下,请移动number
n
向右,然后按位与:
// bool requires #include <stdbool.h> prior to C23
inline bool bit_check(Uint number, Uint n) {
return (number >> n) & (Uint)1;
}
改变n第 位到x
有一些代码生成更差的替代方案,但最好的方法是清除该位,如bit_clear
,然后将该位设置为值,类似于bit_set
.
inline Uint bit_set_to(Uint number, Uint n, bool x) {
return (number & ~((Uint)1 << n)) | ((Uint)x << n);
}
所有解决方案都经过测试,可以通过 GCC 和 clang 提供最佳的代码生成。看https://godbolt.org/z/Wfzh8xsjW.