C++ XOR Operator

C++ xor operator is discussed in this article.

XOR operator is bitwise operator in c programing language. This operator acts like a function, it takes two numbers and performs xor operator on each bit of two numbers.

C++ XOR Operator

A number (say) 4 is 0100 and 3 in binary is 0011.

If any one bit of two input bits is 1 then result is 1, if both bits are 1 then result if 0.

  0100
  0011
  ----
  0111  <-- result
  

Look the example above, each bit is compared to corresponding bit of other number and xor is performed.

Like i said in begining if one bit is 1 then its 1, if both bits are 1 then result is 1.

Again, we took two numbers, converted to binary and then performed xor operation.

Even if you did 4 xor 3 in c programming using natural numbers the result is 7 (0111) because internally the number is converted to binary then xor is performed.

Now i forgot to tell you the symbol which is used to represent xor operator.

XOR operator in C or C++ programming lanuage is denoted by ^.

XOR demonstration in C++ Program

#include <iostream>
using namespace std;

int main() {
	int first_number = 4, second_number = 3;

	cout << "first_number ^ second_number = " << (first_number ^ second_number) << endl;

	return 0;
}

Output

first_number ^ second_number = 7

Comments