In this tutorial, we will learn Bit masking in C++ with a program.

We are well aware of the bitwise operators in C++. They are – bitwise and, or, not and exclusive or operators. We use bitmask operations to turn a bit on from off or vice-versa, check if a bit is on or off and for toggling a bit.

## Why do we use bit masking?

We use bit masking to store multiple layers of values in the same set of numbers. Let us understand this with an example:

consider the set S={1,2,3,4,5,6,7}.

To represent the set{2,3,5}, we can use the bitmask 0110100.

Bitmasks can be used for the following operations:

### To set the ith bit:

Let us consider a value x. We perform x |=x<<i for setting a bit. To put it simply, we left shift x by i bits, and perform the bitwise operation, as it ideally does not change values.

### To unset the ith bit:

We use x&=~(x<<i).

### To toggle a bit:

For this, we use the operation x^=x<<i.

## Bit masking program in C++

```#include<iostream>
using namespace std;
{
int i;
cout<<"which position do you want to set?";
cin>>i;
cout<<"before "<<x<<endl;
x|=x<<i;
cout<<"after "<<x<<endl;

}

{
int i;
cout<<"enter the position you want to clear: ";
cin>>i;
cout<<"before clearing: "<<x<<endl;
x&=~(x<<i);
cout<<"after clearing: "<<x<<endl;

}

void toggle_bit(int x)
{
int i;
cout<<"Which bit do you want to toggle? ";
cin>>i;
cout<<"before toggle: "<<x<<endl;
x^=x<<i;
cout<<"After toggle: "<<x<<endl;
}

int main()
{
int num,ch;
cout<<"enter a number: ";
cin>>num;
while(1)
{
cin>>ch;
switch(ch)
{
break;
break;
case 3:toggle_bit(num);
break;
default:cout<<"invalid choice"<<endl;
break;

}

}

return 0;

}```
```Output:
enter a number: 24
3.TOGGLE BIT

which position do you want to set?4
before 24
after 408
3.TOGGLE BIT

enter the position you want to clear: 4
before clearing: 24
after clearing: 24
3.TOGGLE BIT

Which bit do you want to toggle? 2
before toggle: 24
After toggle: 120
3.TOGGLE BIT