C++ - Bitwise XOR operator
The Bitwise XOR operator (^) is a binary operator which takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. It returns 1 if only one of the bits is 1, else returns 0.
Bit_1 | Bit_2 | Bit_1 ^ Bit_2 |
---|---|---|
0 | 0 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 0 |
The example below describes how bitwise XOR operator works:
50 ^ 25 returns 43 50 -> 110010 (In Binary) ^ 25 -> ^ 011001 (In Binary) ---- -------- 43 <- 101011 (In Binary)
The code of using Bitwise XOR operator (^) is given below:
#include <iostream> using namespace std; int main (){ int x = 50; int y = 25; int z; //Bitwise XOR operation z = x ^ y; //Displaying the result cout<<"z = "<<z; return 0; }
The output of the above code will be:
z = 43
Example: Swap two numbers without using temporary variable
The bitwise XOR operator can be used to swap the value of two variables. Consider the example below.
#include <iostream> using namespace std; static void swap(int x, int y) { cout<<"Before Swap.\n"; cout<<"x = "<<x<<"\n"; cout<<"y = "<<y<<"\n"; //Swap technique x = x ^ y; y = x ^ y; x = x ^ y; cout<<"After Swap.\n"; cout<<"x = "<<x<<"\n"; cout<<"y = "<<y<<"\n"; } int main() { swap(10, 25); return 0; }
The above code will give the following output:
Before Swap. x = 10 y = 25 After Swap. x = 25 y = 10
❮ C++ - Operators