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 of operand1 and operand2 are different, and 0 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:

  1. a = 10 (Binary: 1010) and b = 6 (Binary: 0110).
  2. The XOR operation compares each bit of a and b. If the bits are different, the result is 1; otherwise, it is 0.
  3. 1010 XOR 0110 = 1100 (Decimal: 12).
  4. The result 1100 is stored in the variable result.

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:

  1. The variable num is 5 (Binary: 0101), and the mask is 1 (Binary: 0001).
  2. The XOR operation toggles the least significant bit of num, effectively changing its parity.
  3. If the toggled result matches num - 1, the number is odd; otherwise, it is even.

Key Points about xor keyword

  1. The xor keyword is equivalent to ^ and is used for bitwise XOR operations.
  2. It returns 1 for each bit position where the corresponding bits of the operands are different, and 0 otherwise.
  3. xor is an alternative token in C++ and is rarely used in modern code as ^ is more common and concise.