0

I understand the idea and concept of XOR outside of code. But I wanted an easy explanation when it's used in code. Let me give you a few examples of what I'm having trouble understanding.

Say we wanted to Swap internet values in C++ with out using a third temp variable and by using XOR, like so:

int a = 1;
int b = 3;

int *x = &a;
int *y = &b;

*x ^= *y;
*y ^= *x;
*x ^= *y; 

Now I understand that *x ^= y translates to *x = *x ^ *y But I just need to understand one line only to understand the rest. Basically, in *x = *x ^ *y why is *y always being set to *x in order to being the swap sequence? (Or am I getting that part wrong too?) How is *y being exclusively chosen and on what criteria?

Ebad Saghar
  • 1,107
  • 2
  • 16
  • 41
  • Your example is faulty: ^ = is not ^= operator. Also, int *x=&a and int *y=&b; – George Houpis Dec 20 '14 at 21:35
  • 1
    That is the [XOR swap algorithm](http://en.wikipedia.org/wiki/XOR_swap_algorithm). Try writing out the bit sequences before and after that line if you don't follow it. – Elliott Frisch Dec 20 '14 at 21:35
  • _"Say we wanted to Swap internet values ..."_ Are you talking about network byte oder actually? – πάντα ῥεῖ Dec 20 '14 at 21:36
  • 1
    unrelated, but `int *x = a` is wrong, you want `int *x = &a`. Also, XOR swapping is a trick that one shouldn't use, the compiler optimize better that most of us. Also, the XOR swapping doesn't work whenever `x` and `y` point to the same object. – vsoftco Dec 20 '14 at 21:36
  • You could also use add and subtract, to swap two integers a and b: | a = a + b; | b = a - b; | a = a - b; | . – rcgldr Dec 20 '14 at 21:52

0 Answers0