Bitwise Operators

Let’s discuss bitwise operators in this lesson.

Introduction

A bitwise operator performs bit by bit processing on the operands.

Bitwise operators operate on binary numbers. They convert operands in decimal form into binary form, perform the particular bitwise operation, and then return the result after converting the number back into decimal form.

Here is the list of bitwise operators available in C++:

Example program with bitwise operators

Consider two operands of type int. The value of operand1 is 3, and the value of operand2 is 2. The program given below demonstrates the use of bitwise operators.

Run the code below and see the output!

Press + to interact
#include <iostream>
using namespace std;
int main() {
int operand1 = 3;
int operand2 = 2;
cout << "operand1 = " << operand1 << " , operand2 = " << operand2 << endl;
cout << "operand1 & operand2 = " << (operand1 & operand2) << endl;
cout << "operand1 | operand2 = " << (operand1 | operand2 )<< endl;
cout << "operand1 ^ operand2 = " << (operand1 ^ operand2) << endl;
return 0;
}

Explanation #

Let’s convert the given decimal numbers into binary.

Bitwise AND

If the corresponding bits in both the operands is 1, it returns 1. Otherwise, it returns 0.

Bitwise OR

If the corresponding bit in at least of the operands is 1, it returns 1. Otherwise, it returns 0.

Bitwise

...