Bitoperators

Bitwise operators are used to process numbers with respect to their binary representation. The main task of bitwise operators is to manipulate binary values bitwise.

The operations are directly supported by the processor. Bitwise operations are required for working with device drivers, low-level graphics, cryptography, and network communication.

OperatorDescription
~Bit complement
<<Left shift of bit patterns
>>Right shift of bit patterns
&Bitwise AND
^Bitwise XOR
|Bitwise OR

Code Example

#include <iostream>
using namespace std;

int main() {
	int x, y, z, a=7, b=12, c=15;
	x = a & b;
	z = a | b;
	y = a ^ c;
	cout << "Bitwise AND: " << x << endl;
	cout << "Bitwise OR: " << z << endl;
	cout << "Bitwise XOR: " << y << endl;
}
Output

The output shows the results of the bitwise operations between the variables a, b, and c. The value of x is 4, which is the result of a & b. The value of z is 15, which is the result of a | b. The value of y is 8, which is the result of a ^ c.

Bitwise AND: 4
Bitwise OR: 15
Bitwise XOR: 8

Code Explanation

  1. Inside the main() function, several variables are declared:
    • x, y, and z are int variables that will store the results of the bitwise operations.
    • a is an int variable initialized with the value 7.
    • b is an int variable initialized with the value 12.
    • c is an int variable initialized with the value 15.
  2. The line x = a & b; performs a bitwise AND operation between a and b and assigns the result to x. The bitwise AND operator (&) compares the corresponding bits of a and b and returns a new value where each bit is set to 1 if both corresponding bits in a and b are 1, otherwise it sets the bit to 0.
  3. The line z = a | b; performs a bitwise OR operation between a and b and assigns the result to z. The bitwise OR operator (|) compares the corresponding bits of a and b and returns a new value where each bit is set to 1 if at least one of the corresponding bits in a and b is 1, otherwise it sets the bit to 0.
  4. The line y = a ^ c; performs a bitwise XOR (exclusive OR) operation between a and c and assigns the result to y. The bitwise XOR operator (^) compares the corresponding bits of a and c and returns a new value where each bit is set to 1 if the corresponding bits in a and c are different, otherwise it sets the bit to 0.
  5. The cout statements are used to display the results of the bitwise operations on the console. They use the << operator to insert values and strings into the output stream.
  6. Each cout statement outputs a string describing the bitwise operation performed (Bitwise AND:, Bitwise OR:, Bitwise XOR:), followed by the result of the operation (x, z, y).