Related Tags

basics
bitwise
operation
c++
java

# Bitwise operators

Bitwise operators work efficiently and are used to perform bitwise operations on binary patterns. All the binary operators are in-fix except for the not operator.

The infix operator performs an â€‹operation on the corresponding pair of bits, where each pair contains one bit from each operand.

## Types of bitwise operators

operator description example
& (AND) The bits that are set in both operands are set. (10101010) & (11111111) = (10101010)
| (OR) The bits that are set in either of the two operands are set. (10101010) | (11111111) = (11111111)
^ (XOR) The bits that are set in only one (not both) of the operands are set. (10101010) ^ (11111111) = (01010101)
~ (NOT) Its a unary operator and the bits that are set will be unset. ~ (10101010) = (01010101)
<< (SHIFT LEFT) It shifts the bits of operand1 to the left operand2 times (10101010) << (00000011) = (01010000)
>> (SHIFT RIGHT) It shifts the bits of operand1 to the right operand2 (10101010) >> (00000011) = (00001010)

## Code

#include <iostream>
#include <bitset>
using namespace std;

int main() {
int x = 12; // (00001100)
int y = 6;  // (00000110)
// using bitset() fucntion to print
// in binary form
cout << "x = " << bitset<8>(x) << "\n";
cout << "y = " << bitset<8>(y) << "\n";
// and operator
cout << "x & y is equal to " << bitset<8>(x & y) << "\n";
// or operator
cout << "x | y is equal to " << bitset<8>(x | y) << "\n";
// xor operator
cout << "x ^ y is equal to " << bitset<8>(x ^ y) << "\n";
// shift left operator
cout << "x << y is equal to " << bitset<8>(x << y) << "\n";
// shift right operator
cout << "x >> y is equal to " << bitset<8>(x >> y) << "\n";
// not operator
cout << "~ x is equal to " << bitset<8>(~ x) << "\n";

return 0;
}

RELATED TAGS

basics
bitwise
operation
c++
java
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time