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).

Similar Reads

Setting a Bit

Setting a bit means that if the given K-th bit is 0, then we set it to 1 and if it is 1 then simply ignore it. By performing bitwise OR (‘ | ‘) of a set bit with any bit gives a set bit only, i.e. 0 | 1 = 1 and 1 | 1 = 1. So we can use bitwise OR to set a bit....

Clearing a Bit

Clearing a bit means that if the K-th bit is 1, then we clear it to 0, and if it is 0 then simply ignore it. By performing bitwise AND (‘&’) of a reset bit with any bit gives a reset bit, i.e. 0 & 0 = 0 and 1 & 0 = 0. So, we can use the bitwise AND (&) operator along with the bitwise NOT (~) operator to clear a bit....

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....

C++ Program to Set, Clear and Toggle a Bit

The below example demonstrates how to perform set, clear and toggle operations on a single bit....