+ 1

Can anyone help me with a C++ program to swap values of three variables using bitwise operator??

17th Jan 2017, 1:24 PM
Jake
Jake - avatar
4 Answers
+ 10
Here you go: x=x^y^z; y=x^y^z; z=x^y^z; x=x^y^z;
17th Jan 2017, 2:55 PM
Filip
Filip - avatar
+ 9
And here's the code example: #include <iostream> using namespace std; void swap(int x, int y, int z) { x=x^y^z; y=x^y^z; z=x^y^z; x=x^y^z; cout<<x<<endl<<y<<endl<<z; } int main() { int x=1, y=2, z=3; swap(x, y, z); return 0; }
17th Jan 2017, 2:56 PM
Filip
Filip - avatar
+ 7
You can use XOR (exclusive or). example code: x = x XOR y XOR z; y = x XOR y XOR z; z = x XOR y XOR z; x = x XOR y XOR z;
17th Jan 2017, 2:22 PM
Karl T.
Karl T. - avatar
+ 6
Swapping values are easy, but I'm not familiar with using bitwise operators. May need someone better to come across this thread.
17th Jan 2017, 1:30 PM
Hatsy Rei
Hatsy Rei - avatar