Open In App

Set, Clear and Toggle a given bit of a number in C

Given a number N, the task is to set, clear and toggle the K-th bit of this number N.

Examples:



Input: N = 5, K = 1
Output: 
Setting Kth bit: 5
Clearing Kth bit: 4
Toggling Kth bit: 4
Explanation: 
5 is represented as 101 in binary
and has its first bit 1, so 
setting it will result in 101 i.e. 5.
clearing it will result in 100 i.e. 4.
toggling it will result in 100 i.e. 4.

Input: N = 7, K = 2
Output: 
Setting Kth bit: 7
Clearing Kth bit: 5
Toggling Kth bit: 5
Explanation: 
7 is represented as 111 in binary
and has its second bit 1, so 
setting it will result in 111 i.e. 7.
clearing it will result in 101 i.e. 5.
toggling it will result in 101 i.e. 5.

Approach:

Below are the steps to set, clear and toggle Kth bit of N:



Setting a bit

Clearing a bit

Toggle a bit

Below is the implementation of the above approach:




// C program to set, clear and toggle a bit
  
#include <stdio.h>
  
// Function to set the kth bit of n
int setBit(int n, int k)
{
    return (n | (1 << (k - 1)));
}
  
// Function to clear the kth bit of n
int clearBit(int n, int k)
{
    return (n & (~(1 << (k - 1))));
}
  
// Function to toggle the kth bit of n
int toggleBit(int n, int k)
{
    return (n ^ (1 << (k - 1)));
}
  
// Driver code
int main()
{
    int n = 5, k = 1;
  
    printf("%d with %d-th bit Set: %d\n",
           n, k, setBit(n, k));
    printf("%d with %d-th bit Cleared: %d\n",
           n, k, clearBit(n, k));
    printf("%d with %d-th bit Toggled: %d\n",
           n, k, toggleBit(n, k));
    return 0;
}

Output:
5 with 1-th bit Set: 5
5 with 1-th bit Cleared: 4
5 with 1-th bit Toggled: 4

Article Tags :