To toggle a bit we will use bitwise XOR ^ operator. Bitwise XOR operator evaluates to 1 if corresponding bit of both operands are different otherwise evaluates to 0 .
How do you toggle a bit?
- Setting a bit. Use the bitwise OR operator ( | ) to set a bit. number |= 1 << x; That will set a bit x .
- Clearing a bit. Use the bitwise AND operator ( & ) to clear a bit. number &= ~(1 << x); That will clear bit x . ...
- Toggling a bit. The XOR operator ( ^ ) can be used to toggle a bit. number ^= 1 << x;
Which operator is a bit wise and operator?
The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise AND operator must have integral types.