Swapping Integers Using XOR operation

Swapping Integers Using XOR Operation


C++ : Swapping integers using XOR operations. Implemented in C++11

#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 showing the swapping of integers using XOR operations

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

Copyright © 2020, Algotree.org.
All rights reserved.