Toggling a Bit
Toggling a bit means that if the K-th bit is 1, then we change it to 0 and if it is 0 then change it to 1. By performing XOR (‘^’) of set and unset gives a set bit and XOR of a set and set bit or unset and unset bits gives an unset bit, i.e. 0 ^ 1 = 1 and 1 ^ 1 = 0. So we can use XOR to toggle a bit.
Formula:
number ^= 1 << bit_position;
How to Set, Clear, and Toggle a Single Bit in C++?
In bit manipulation, setting a bit, clearing a bit, and toggling a single bit are basic operations. We can easily carry out these operations using the bitwise operators in C++.
In this article, we will see how to set, clear, and toggle operations on the Kth bit.
Example
Input: N = 15, K = 0
Output:
Setting Kth bit: 15
Clearing Kth bit: 14
Toggling Kth bit: 14
Explanation: 15 is represented as 1111 in binary and has its first bit 1. Setting it will result in 1111 (15 in decimal). Clearing it will result in 1110 (14 in decimal). Toggling it will result in 1110 (14 in decimal).