Home »
C++ programs
C++ program to clear Kth bit of a number
Program to clear the Kth bit of a number in C++: Here, we are going to use bitwise operators to clear Kth bit in the binary representation of a given number.
Submitted by Saksham Bhayana, on January 07, 2019
Here we are going to use bitwise operators to clear Kth bit in the binary representation of a given number.
Problem Statement: To write a C++ program to clear Kth bit of a number.
Constraints: 1<=n<=100
Example:
Input:
Enter number: 11
Enter k: 4
Output:
original number before clearing: 11
new number after clearing: 3
Problem Explanation:
Suppose the given number is 11 and the bit to be cleared is 4th bit that is 3 left to the LSB.
Now the binary representation of 11 is:
n = 00001011
mask = 00001000 (left shift 1, three times (4-1) as k=4)
Bitwise complement of mask= ~mask = 11110111
n &(~ mask) = 00000011
Hence decimal representation of new number is 3.
This can be explained as follows:
Performing & with the ~mask clears Kth bit only as Kth bit in (~mask) is 0.
If X represents bits of n then, 0 & X is always 0. For remaining bits of original number, & with 1 gives the bit itself.
Therefore performing bitwise AND of original number with (~mask) clears Kth bit in a number.
Algorithm:
- Input the number and Kth bit to be cleared.
- Left shift 1 - (K-1) times to create a mask where only Kth bit is set.
- Take bitwise complement of the mask.
- Perform bitwise AND of original number with this mask to clear the Kth bit.
- Output the result after bitwise AND in decimal form.
C++ Implementation:
#include <iostream>
using namespace std;
int clearKthBit(int n,int k)
{
// left shift 1 , (k-1) times to get a mask
// in which only kth bit is set
int m=1<<(k-1);
// bitwise complement of mask
m=~(m);
// new number after clearing kth bit
return (n&m);
}
//driver program to check the code
int main()
{
int num,k;
cout<<"Enter number: ";
cin>>num;
cout<<"Enter k: ";
cin>>k;
cout<<"original number before clearing: "<<num<<endl;
int new_number= clearKthBit(num,k);
cout<<"new number after clearing: "<<new_number<<endl;
return 0;
}
Output
Enter number: 11
Enter k: 4
original number before clearing: 11
new number after clearing: 3