Use the bitwise OR operator (|) to set nth bit of 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);
}
Note that it's undefined behavior to shift by more than the width of a Uint. The same applies to all remaining examples.
Clearing a bit
Use the bitwise AND operator (&) to set the nth bit of number to 0.
Best Answer
Setting a bit
Use the bitwise OR operator (
|
) to setn
th bit ofnumber
to1
.Note that it's undefined behavior to shift by more than the width of a
Uint
. The same applies to all remaining examples.Clearing a bit
Use the bitwise AND operator (
&
) to set then
th bit ofnumber
to0
.You must invert the bit string with the bitwise NOT operator (
~
), then AND it.Toggling a bit
Use the bitwise XOR operator (
^
) to toggle then
th bit ofnumber
.Checking a bit
You didn't ask for this, but I might as well add it.
To check a bit, shift
number
n
to the right, then bitwise AND it:Changing the nth bit to x
There are alternatives with worse codegen, but the best way is to clear the bit like in
bit_clear
, then set the bit to value, similar tobit_set
.All solutions have been tested to provide optimal codegen with GCC and clang. See https://godbolt.org/z/Wfzh8xsjW.