How can I set, clear, and toggle a bit?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Setting a bit
Use the bitwise OR operator (
|) to setnth bit ofnumberto1.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 thenth bit ofnumberto0.You must invert the bit string with the bitwise NOT operator (
~), then AND it.Toggling a bit
Use the bitwise XOR operator (
^) to toggle thenth bit ofnumber.Checking a bit
You didn’t ask for this, but I might as well add it.
To check a bit, shift
numbernto 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.