Bit Masking in C++
In this tutorial, we will learn Bit masking in C++ with a program.
What is a bitmask?
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.
Using Bitmasks in C++
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; void set_mask(int x) { int i; cout<<"which position do you want to set?"; cin>>i; cout<<"before "<<x<<endl; x|=x<<i; cout<<"after "<<x<<endl; } void unset_mask(int x) { 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) { cout<<"your choices are: 1.SET MASK\n 2.UNSET/CLEAR MASK\n 3.TOGGLE BIT\n"<<endl; cout<<"enter your choice: "; cin>>ch; switch(ch) { case 1:set_mask(num); break; case 2:unset_mask(num); break; case 3:toggle_bit(num); break; default:cout<<"invalid choice"<<endl; break; } } return 0; }
Output: enter a number: 24 your choices are: 1.SET MASK 2.UNSET/CLEAR MASK 3.TOGGLE BIT enter your choice: 1 which position do you want to set?4 before 24 after 408 your choices are: 1.SET MASK 2.UNSET/CLEAR MASK 3.TOGGLE BIT enter your choice: 2 enter the position you want to clear: 4 before clearing: 24 after clearing: 24 your choices are: 1.SET MASK 2.UNSET/CLEAR MASK 3.TOGGLE BIT enter your choice: 3 Which bit do you want to toggle? 2 before toggle: 24 After toggle: 120 your choices are: 1.SET MASK 2.UNSET/CLEAR MASK 3.TOGGLE BIT enter your choice:
You may also learn:
This does’nt explain what a bitmask actually is.
“Toggle a bit: x^=x<<i"
Did you meant "x ^= 1 << i" instead ?