ReferenceHow does the set, clear and toggle a single bit in C?
The operations on BITS in C + + include setting a bit to 1, clearing a bit (set to 0), switching a bit (toggling a bit), checking if a bit is 1, and so on. These operations are more common and can be used as the underlying interface for other bit operations, and there are several methods listed below:
Traditional methods
number |= 1 << x; // 设置第x位为1
number &= ~(1 << x); // 置第x位为0
number ^= 1 << x;
if (number & (1 << x))
Accordingly, we can encapsulate it in a convenient way by using a macro to encapsulate:
#define BIT_SET(a,b) ((a) |= (1<<(b)))#define BIT_CLEAR(a,b) ((a) &= ~(1<<(b)))#define BIT_FLIP(a,b) ((a) ^= (1<<(b)))#define BIT_CHECK(a,b) ((a) & (1<<(b)))
Using bit structure operations
This is a lot easier to use:
structBits{UnsignedIntA:1;UnsignedIntB:1;UnsignedIntC:1;};structBitsMybits;Set/clear a bitMybits.B=1;mybits. C = 0; Toggle a Bitmybits. A = ! Mybits. A; Mybits. b = ~mybits. B; Mybits. C ^= 1; Check a bitif (mybits. C)
Using STL's Std::bitset
This approach is similar to using a bit structure, except that STL wraps the structure definition and, of course, provides a lot of convenient interfaces:
Std::bitset<5> bits; Bits[0] = true ; bits[1] = False; Bits. Set (2. Flip (3. Reset (2
The methods of several operation bits in C + +