Open In App

How to Set, Clear, and Toggle a Single Bit in C++?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

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.

Formula:

number |= 1 << bit_position

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.

Formula:

number &= ~(1 << bit_position);

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;

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.

C++




// C++ program to demonstrate how to perform set, clear and
// toggle operations on a single bit.
  
#include <iostream>
using namespace std;
  
// Function to set the kth bit of n
int setBit(int n, int k) { return (n | (1 << (k))); }
  
// Function to clear the kth bit of n
int clearBit(int n, int k) { return (n & (~(1 << (k)))); }
  
// Function to toggle the kth bit of n
int toggleBit(int n, int k) { return (n ^ (1 << (k))); }
  
int main()
{
    int n = 15, k = 0;
  
    cout << n << " with " << k
         << "-th bit Set: " << setBit(n, k) << endl;
    cout << n << " with " << k
         << "-th bit Cleared: " << clearBit(n, k) << endl;
    cout << n << " with " << k
         << "-th bit Toggled: " << toggleBit(n, k) << endl;
  
    return 0;
}


Output

15 with 0-th bit Set: 15
15 with 0-th bit Cleared: 14
15 with 0-th bit Toggled: 14





Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads