To Set / Clear and Toggle a single bit in C++ see the methods below.

Setting a bit

Use the bitwise OR operator (|) to set a bit.

number |= 1 << x;

Clearing a bit

Use the bitwise AND operator (&) to clear a bit.

number &= ~(1 << x);

Toggling a bit

The XOR operator (^) can be used to toggle a bit.

number ^= 1 << x;

Source

7 thought on “How to Set / Clear and Toggle a single bit in C/C++”

Leave a Reply