×

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described as a mask of an N-bit sequence used to encrypt a particular portion of our collection. These mask components can be fixed or cannot be restored. To create or toggle the bits, there are bitwise operators. These operators are employed to activate the off bit or its opposite.

You must have the Ubuntu file configured and active to use C++ programmes under Linux execution. The user also must be familiar with the C++ programming language. Source code for C++ is written.The text editor is used to create the C++ source codes. Use the Ubuntu terminal for the execution process.

A bitmask is a straightforward mask that consists of an n-bit sequence. It encodes the collection's subset. The mask's "ith" bit is set, and the element "I" is present in that subset. There is a possibility of finding a 2N cover that corresponds to a subset of the set of features holding the nth byte.

The purpose of bit masking

Different values are stored in the same set of integers during the bit masking process. Consider a set, for instance, where s = 1, 2, 5, 8, 6, and 7. Any bitmask 010110 can be used to represent the set of "2, 5, 7."

The following are the operations that bitmaps carry out:

Toggle the "ith" bit

To do this, consider the value "x". We can use the operation x|=xi to set a bit. After performing the bitwise operation, we shift 'a' left bit by bit.

Remove the "ith" bit.

A bit that has already been set by the user or default must exist to unset the bit. In this way, it is simple to reset that specific bit. Therefore, we employ the operators x&= (x I for that.

Modify a little

In this procedure, we apply the operator x=xi.

In plain English, setting a bit entails setting it to 1. Suppose the i-th bit is 0, otherwise to 0. Additionally, if it already equals 1, leave it alone. If the i-th bit is 1, the bit clearance should clear it to 0. If it already has a value of 0, don't modify it; leave it alone. Whenever a bit needs to be toggled, if the i-th bit is 1, convert it to 0. If it is already 0, you must alter it back to 1 once more.

Illustration of bit masking

Here, we attempt to describe bit masking's operation using its most fundamental idea. All three-bit masking operations that were previously discussed in this tutorial are used in this example.

Let's begin by reading from and writing to the file using the input and output streams.

#include<iostream>

To make the source code more comprehensible and orderly, we first jumped to the main programme. Additionally, it will help those who are new to programming comprehend the subject better. The entire mechanism of this programme is user interactive. This requires user participation in the whole system's operation. The user is prompted for the number on which operations are to be applied as the first step in the main programme. A variable is pre-set to accept the user-provided value before the question.

int main ()
{
      Int num,ch;
Cout<<”enter a number:” ;
Cin>>num;
      While (1)
      {
Cout<<”your choices are:\n 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;
           }
}

Numerous operations are performed on the entered number, including the use of a while loop. Every time the programme is run, the availability of numbers is guaranteed by this loop. When a number is entered, the system gives the user three choices: toggling the value, setting a bitmask, and clearing a bitmask. Finally, a person is prompted to choose one of them. We need logic that will only select the first option the user enters to move through all of these procedures. At that time, all operations are stopped.

This is when a switch statement is used. The user's selection is saved in a variable after being entered, and a switch statement is then run on that variable. A function call for each option is contained on each line of the switch statement. The system will run the specific programme for whichever choice the user chooses. With each switch statement option, a break statement is used. Because after completing one choice, you must automatically halt the software from running until you ask it to do so.

Now think about the first possibility; the first function is concerned with setting a mask. It includes the variable needed to store the user-inputted number. To supply the value before and after the bit value, this number will be subjected to an arithmetic operation.

X|x<<I ;
#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;
   }

The value is processed once more when all the procedures have been completed, and then the value is shown.

The next option is to reset the newly created or existing mask. Additionally, this will erase the bit's first and second-most essential values.

X&=~(x<<i);

To help the user understand the notion, we have broken down each function into its own section. Additionally, this will give the bitmask's initial and subsequent values.

X^=x<<I;
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;
}

Save the code in the file after you've finished writing it, then save the file with the extension “. c." We require a "g++" compiler to compile the code before we can run it. The file's name is "bit. C."

Bitmasking in C++ Bitmasking in C++

When the code is executed, the control is in the main programme when you choose a function. Then, in accordance with the process, a call to a specific function is made, and control is transferred to that function. For instance, as seen in the image, we enter the number first, followed by the option.

Line-by-line, we shall choose all three possibilities. To set the bitmask, we have first determined the first option. When the execution of the function is complete, a bit before and after the current bit is printed at random.

Bitmasking in C++

The choices are again shown. We now wish to remove the setting for "3." Again, the value is shown before and after clearing.

Bitmasking in C++

Select the toggle option at the end of the choice list when you see it again. Enter the bit that needs to be switched. The values of the preceding and subsequent toggles will be shown.

Bitmasking in C++

If you keep entering option values, this process will continue. To shut off the computer, press "Ctrl + C."

The iteration procedures benefit from the bit masking technique. We've provided a succinct illustration to demonstrate how to set, unset, and toggle the mask. The example can also be modified to fit the requirements of our programme. We hope that this information may aid in your comprehension of the bit masking process.


Related Topics

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples. What is the While Loop? The “while loop” is a...

4 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

Bits stdc++.h in C++

<bits/stdc++.h> in C++ In essence, it is a header file that contains all the standard libraries. It makes sense to use this file in programming competitions to speed up work, especially...

2 minutes read.

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 minutes read.