Swapping Integers Using XOR operation

Swapping Integers Using XOR Operation

XOR or Exclusive OR is a logical operation that works on 2 binary values. The result of an XOR operation on 2 bits follows the below rules.
a) If the bits are same i.e both 0 or both 1 then the result of XOR is 0.
b) If the bits are different i.e 0 and 1, then the result of XOR is 1.

XOR_Integer_Swap



C++ : Swapping integers using XOR operations.

#include<iostream>
#include<bitset>
#include<cstdio>

using namespace std;

class Bits {

    public:
    void Swap(int &a , int &b) {
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
    }
};

int main() {

    Bits B;
    int a = -5;
    int b = 8;

    cout << "Before : " <<  a << " " << b << endl;
    B.Swap(a, b);
    cout << "After Swap : " <<  a << " " << b << endl;

    a = -256;
    b = 16384;

    cout << "Before : " <<  a << " " << b << endl;
    B.Swap(a, b);
    cout << "After Swap : " <<  a << " " << b << endl;

    return 0;
}

Output

Before : -5 8
After Swap : 8 -5
Before : -256 16384
After Swap : 16384 -256


Copyright (c) 2019-2021, Algotree.org.
All rights reserved.