|
|
|
|
|
by cyberferret
3417 days ago
|
|
Very early on in my computing career (nearly 40 years ago now), I remember being blown away when an older IBM Systems 360 programmer showed me how you can swap the values of two variables over WITHOUT using a third placeholder variable by using pure XOR. I didn't believe him until he showed me. Apparently they used to use it all the time to swap out entire segments of RAM in the S/360 without having to page out to disk or clobber other free RAM segments. It is simply: a = a xor b
b = b xor a
a = a xor b
Three steps, same as using a placeholder 'c' variable. I think he mentioned on most of the processors of the time, 3 XOR instructions actually worked faster than 3 MOV instructions.Illustration for the non-believers: a = 10010110
b = 01100011
a = a xor b
a = 11110101
b = 01100011 (unchanged)
b = b xor a
a = 11110101 (unchanged)
b = 10010110
a = a xor b
a = 01100011
b = 10010110
Voila! |
|
However, the semantics differ from just using a temporary variable in that if a and b are in the same memory location then the result will be zero.
This was used in an entry for the underhanded C contest [1] if I remember correctly where for an implementation of RC4 the author defined the following macro.
And used it for swapping the values in the substitution table for the cipher, e.g. SWAP(S[i], S[j]). The weakness was that since sometimes the indices are the same in RC4 the substitution table would be gradually replaced with zeroes.[1] http://www.underhanded-c.org/_page_id_16.html