Find XOR of two number without using XOR operator in C++


In this problem, we are given integer values A & B. Our task is to find XOR of two numbers without using the XOR operator.

Let's take an example to understand the problem,

Input : A = 4, B = 5
Output : 1

Solution Approach

One method to solve the problem is by converting the numbers to their respective binary numbers and then performing bitwise operations based on this table.

ABOutput
000
011
101
110

This will return the result. For this we will use bitwise operations.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int calcXORwoOperator(int a, int b){
   int xorVal = 0;
   for (int i = 31; i >= 0; i--){
      bool val1 = a & (1 << i);
      bool val2 = b & (1 << i);
      bool xorBit = (val1 & val2) ? 0 : (val1 | val2);
      xorVal <<= 1;
      xorVal |= xorBit;
   }
   return xorVal;
}
int main(){
   int a = 4, b = 5;
   cout<<"XOR of the numbers is "<<calcXORwoOperator(a, b);
   return 0;
}

Output

XOR of the numbers is 1

Alternated method

Another method to find the xor is the comparison between the bits present in both numbers one by one and performing operations equivalent to XOR on them.

The expression (a | b) - (a & b) is equivalent to a^b. So, we will perform this operation. Thereby finding XOR of two numbers a & b.

Example

Program to illustrate the working of our solution

#include <iostream>
#include <bitset>
using namespace std;
int calcXORwoOperator(int a, int b) {
   return (a | b) - (a & b);
}
int main(){
   int a = 4;
   int b = 5;
   cout<<"The XOR of both numbers is "<<(bitset<8>(calcXORwoOperator(a, b)));
   return 0;
}

Output

The XOR of both numbers is 00000001

Updated on: 01-Feb-2022

730 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements