How do you set, clear, and toggle a bit in C/C++?
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
Use this:
Use one of the operators as defined here.
To set a bit, used
int x = x | 0x?;
where?
is the bit position in binary form.Setting a bit
Use the bitwise OR operator (
|
) to set a bit.That will set the
n
th bit ofnumber
.n
should be zero, if you want to set the1
st bit and so on upton-1
, if you want to set then
th bit.Use
1ULL
ifnumber
is wider thanunsigned long
; promotion of1UL << n
doesn't happen until after evaluating1UL << n
where it's undefined behaviour to shift by more than the width of along
. The same applies to all the rest of the examples.Clearing a bit
Use the bitwise AND operator (
&
) to clear a bit.That will clear the
n
th bit ofnumber
. You must invert the bit string with the bitwise NOT operator (~
), then AND it.Toggling a bit
The XOR operator (
^
) can be used to toggle a bit.That will toggle the
n
th bit ofnumber
.Checking a bit
You didn't ask for this, but I might as well add it.
To check a bit, shift the number n to the right, then bitwise AND it:
That will put the value of the
n
th bit ofnumber
into the variablebit
.Changing the nth bit to x
Setting the
n
th bit to either1
or0
can be achieved with the following on a 2's complement C++ implementation:Bit
n
will be set ifx
is1
, and cleared ifx
is0
. Ifx
has some other value, you get garbage.x = !!x
will booleanize it to 0 or 1.To make this independent of 2's complement negation behaviour (where
-1
has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.or
It's generally a good idea to use unsigned types for portable bit manipulation.
It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like the community wiki answer further down) or some sort of encapsulation.
This program is to change any data bit from 0 to 1 or 1 to 0:
I use macros defined in a header file to handle bit set and clear:
The bitfield approach has other advantages in the embedded arena. You can define a struct that maps directly onto the bits in a particular hardware register.
You need to be aware of the bit packing order - I think it's MSB first, but this may be implementation-dependent. Also, verify how your compiler handlers fields crossing byte boundaries.
You can then read, write, test the individual values as before.