How to Set / Clear and Toggle a single bit in C/C++

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

Please Share us:
Please rate this snippet

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

Leave a Reply