How to turn off a particular bit in a number in C++ ?
In this tutorial, we will see how to turn off a particular bit in a number in C++.
Any number can be represented in its binary form which contains 0s and 1s. And we want to convert a 1 into 0(turn off) at any given position.
Let’s assume a number :
int num = 5; // 5 is 101 in binary int position = 0; // turn off 1 at 0th position // final answer should be 4 as 101 will become 100 which is 4 in decimal.
Let’s take another example:
int num1 = 7; // 7 is 111 in bianry int position = 1; // final answer should be 5 as 111 will become 101 which is 5 in decimal.
Turning off a bit in a number in C++
Here we will use the bitwise operators on the given number. The bitwise operators used are :
- << (left shift) : num << x this statement shifts the bits of the number by x places.
// 9 is 00001001 9 << 2 // left shifting by 2 places // 00100100 result is 32.
- &(bitwise and): num & x this statement does a bitwise and is similar to the logical operator && but on bits.
// 11011 & 01100 // result is 01000
- ~(compliment): ~num gives the compliment of num.
// ~1100110 is 0011001
Now the idea is to left shift 1 to the given position and then take its complement. This will leave us with a number with 0 at the position’s bit and the rest of the bits as 1. Then take bitwise and (&) of this with the given number. The & operator will turn off the position’s bit as it is 0.
The code using the above operators is given below:
#include <bits/stdc++.h> using namespace std; int main() { int num = 5; // 5 is 101 int position = 0; // result should be 100 which is 4 in decimal cout<<(num & ~(1<<position)) ; return 0; }
Output:
4
Leave a Reply