C++ xor
The xor
keyword in C++ is an alternative representation for the bitwise XOR operator (^
). It is part of the alternative tokens provided by C++ for operators, designed to enhance readability or compatibility with certain keyboard layouts. The xor
operator performs a bitwise exclusive OR operation between two operands.
The xor
operator compares corresponding bits of two operands. If the bits are different, the result is 1
; if the bits are the same, the result is 0
.
Syntax
</>
Copy
result = operand1 xor operand2;
- operand1
- The first operand to be used in the XOR operation.
- operand2
- The second operand to be used in the XOR operation.
- result
- The result of the bitwise XOR operation, where each bit is set to
1
if the corresponding bits ofoperand1
andoperand2
are different, and0
otherwise.
Examples
Example 1: Using xor
for Bitwise XOR Operation
In this example, we will use the xor
keyword to perform a bitwise XOR operation on two integers.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int a = 10; // Binary: 1010
int b = 6; // Binary: 0110
int result = a xor b; // Perform XOR
cout << "Result of a xor b: " << result << endl; // Output: 12 (Binary: 1100)
return 0;
}
Output:
Result of a xor b: 12
Explanation:
a = 10 (Binary: 1010)
andb = 6 (Binary: 0110)
.- The XOR operation compares each bit of
a
andb
. If the bits are different, the result is1
; otherwise, it is0
. 1010 XOR 0110 = 1100 (Decimal: 12)
.- The result
1100
is stored in the variableresult
.
Example 2: Checking Odd or Even Using xor
This example shows how the xor
keyword can be used to toggle bits and check for odd or even numbers.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int num = 5; // Binary: 0101
int mask = 1; // Binary: 0001
bool isOdd = (num xor mask) == (num - 1);
cout << "Is the number odd? " << (isOdd ? "Yes" : "No") << endl;
return 0;
}
Output:
Is the number odd? Yes
Explanation:
- The variable
num
is 5 (Binary: 0101), and the mask is 1 (Binary: 0001). - The XOR operation toggles the least significant bit of
num
, effectively changing its parity. - If the toggled result matches
num - 1
, the number is odd; otherwise, it is even.
Key Points about xor keyword
- The
xor
keyword is equivalent to^
and is used for bitwise XOR operations. - It returns
1
for each bit position where the corresponding bits of the operands are different, and0
otherwise. xor
is an alternative token in C++ and is rarely used in modern code as^
is more common and concise.