C++ Bitwise Operators

Bitwise operators in C++ are used to perform operations on individual bits of a binary number. The following are the bitwise operators in C++:

  1. Bitwise AND (&): The bitwise AND operator performs a logical AND operation on each pair of corresponding bits of two integer operands.

Example:

int a = 5, b = 3;
int c = a & b; // c is assigned the value 1 (binary 001)
Sou‮ecr‬:www.theitroad.com
  1. Bitwise OR (|): The bitwise OR operator performs a logical OR operation on each pair of corresponding bits of two integer operands.

Example:

int a = 5, b = 3;
int c = a | b; // c is assigned the value 7 (binary 111)
  1. Bitwise XOR (^): The bitwise XOR operator performs a logical XOR operation on each pair of corresponding bits of two integer operands. The result is 1 if the bits are different and 0 if the bits are the same.

Example:

int a = 5, b = 3;
int c = a ^ b; // c is assigned the value 6 (binary 110)
  1. Bitwise NOT (~): The bitwise NOT operator is a unary operator that flips all the bits of the operand.

Example:

int a = 5;
int b = ~a; // b is assigned the value -6 (binary 111...1010)
  1. Left shift (<<): The left shift operator shifts the bits of the left operand to the left by a number of positions specified by the right operand. The bits that are shifted out of the left end are lost, and zeros are shifted in from the right end.

Example:

int a = 5;
int b = a << 2; // b is assigned the value 20 (binary 10100)
  1. Right shift (>>): The right shift operator shifts the bits of the left operand to the right by a number of positions specified by the right operand. The bits that are shifted out of the right end are lost, and zeros are shifted in from the left end.

Example:

int a = 20;
int b = a >> 2; // b is assigned the value 5 (binary 101)

In summary, bitwise operators in C++ are used to perform operations on individual bits of a binary number. The bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise NOT (~), left shift (<<), and right shift (>>) operators are used to perform logical AND, OR, XOR, NOT, left shift, and right shift operations, respectively.