News for hackers. Stuff that matters.
Re:The Three Ways of XOR by amelius on Monday February 13, 2017 @08:01AM (#13634897)
You can do the same with addition/subtract. Perhaps there is a simpler way, but here is one way to do it:

    a = a + b
    b = b + a
    a = b - a
    b = b - 2*a
Re:The Three Ways of XOR by mcintyre1994 on Monday February 13, 2017 @09:07AM (#13635250)
a = a + b

b = a - b

a = a - b

I think this works too, assuming a+b doesn't overflow.

Re:The Three Ways of XOR by amelius on Monday February 13, 2017 @09:28AM (#13635396)
Good one.

> I think this works too, assuming a+b doesn't overflow.

Well, in two's complement arithmetic (as is used on most architectures), the intermediate overflow can be ignored, and it will work just fine.

Re:The Three Ways of XOR by Sacho on Monday February 13, 2017 @08:19AM (#13634973)
You have to take overflow into account. In most cases, that would make the algorithm not very useful compared to just doing the swap with a third variable.
Re:The Three Ways of XOR by amelius on Monday February 13, 2017 @09:31AM (#13635420)
In two's complement arithmetic, you are basically computing modulo N (N = 2 to the power of the number of bits). So overflow will not interfere with the swap operation.
Re:The Three Ways of XOR by JoeAltmaier on Monday February 13, 2017 @08:24AM (#13634993)
Hm I don't think overflow will apply. Anything it does in an add will be undone by a subtract?

Except that 2a, that might be trouble.

Re:The Three Ways of XOR by mcintyre1994 on Monday February 13, 2017 @09:05AM (#13635231)
Imagine you only had 4 bit numbers (range 0-15) and you tried to do swap 14, 15 (1110, 1111). You can do that with xor but not with the add method, because you can't store a + b without a wider variable.
Re:The Three Ways of XOR by jonsen on Monday February 13, 2017 @09:22AM (#13635353)
15 + 15 gives 14

14 - 15 gives 15

Re:The Three Ways of XOR by mcintyre1994 on Monday February 13, 2017 @09:27AM (#13635382)
The way I wrote this was rubbish, edited. I was trying to get at if you have 1110, 1111 then 1110 + 1111 will overflow, but you could xor them.
Re:The Three Ways of XOR by jonsen on Monday February 13, 2017 @09:47AM (#13635571)

  1110 + 1111 = 1101
  1101 - 1110 = 1111
  1101 - 1111 = 1110
Overflow doesn't matter if you just want to swap.
Re:The Three Ways of XOR by Sacho on Monday February 13, 2017 @11:27AM (#13636476)
(Assuming two's complement arithmetic, as amelius pointed out - I don't know if all programming languages and platforms use it)
Re:The Three Ways of XOR by mcintyre1994 on Monday February 13, 2017 @04:18PM (#13638860)
That's a really smart observation I hadn't made, thanks for explaining!