logoalt Hacker News

Too much discussion of the XOR swap trick

30 pointsby CJeffersonlast Monday at 11:22 AM9 commentsview on HN

Comments

gobdovantoday at 6:53 AM

The XOR trick is only cool in its undefined-behavior form:

a^=b^=a^=b;

Which allegedly saves you 0.5 seconds of typing in competitive programming competitions from 20 years ago and is known to work reliably (on MinGW under Windows XP).

Bonus authenticity: use `a^=a` to zero a register in a single x86 instruction (and makes a real difference for compiler toolchains 30+ years old).

For real now, a very useful application of XOR is its relation to the Nim game [0], which comes in very handy if you need to save your village from an ancient disgruntled Chinese emperor.

[0] https://en.wikipedia.org/wiki/Nim

mmozeikotoday at 6:11 AM

xor swap trick was useful in older simd (sse1/sse2) when based on some condition you want to swap values or not:

  tmp = (a ^ b) & mask
  a ^= tmp
  b ^= tmp
If mask = 0xfff...fff then a/b will be swapped, otherwise if mask = 0 then they'll remain the same.
show 1 reply
praptaktoday at 7:30 AM

Xor swap trick has perfect profile for underhanded C contests. It generally works until a specific condition triggers its failure. The condition is "the arguments are aliases", so for example XOR_SWAP(a[i], a[j]) when i=j.

DeathArrowtoday at 7:45 AM

30 years ago, when I wanted to 0 a register in assembly I used something like xor ah, ah because it was a bit more performant.

stinkbeetletoday at 7:34 AM

You can use this same property of xor to make a double-linked list using just one pointer per item, which is xor of the previous and next item addresses!

ranger_dangertoday at 5:42 AM

> given a list where every value appears exactly twice except one, XOR all the values together and the duplicates cancel out, leaving the unique element

For some reason this reminds me of the Fourier transform. I wonder if it can be performed with XOR tricks and no complicated arithmetic?

show 1 reply