如何设置、清除和切换单个位

2023-11-23

我怎样才能设置、清除和切换一点?


设置一点

使用按位或运算符 (|) 设置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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何设置、清除和切换单个位 的相关文章

随机推荐