Swap two variables using XOR – BetterExplained
It almost seems like magic – the the same statement is repeated 3 times and voila – the values magically swap? Let’s take a closer look. To understand this trick, break the statements into unique values: According to our code, x2 should have y’s original value. Let’s work out the details for the last step: Wow – x2 really does equal y! The swap happened. Now let’s try it out for y1: And tada the trick worked again. x2 and y1 have the swapped answers. Ok, sure, the boolean algebra works out great — but that’s not satisfying. I want to understand it deep down and have it make sense, not be some artifact of the properties of XOR. Let’s take another look: On line 1 we combine x and y (using XOR) to get this “hybrid” and we store it back in x. XOR is a great way to save information, because you can remove it by doing an XOR again. So, this is exactly what we do on line 2. We XOR the hybrid with y, which cancels out all the y information, leaving us only with x. We save this result back into
Most people would swap two variables x and y using a temporary variable, like this: tmp = x x = y y = tmp Here’s a neat programming trick to swap two values without needing a temp: x = x xor y y = x xor y x = x xor y Don’t believe me? Try it out – write in any initial value for x and y: It almost seems like magic – the the same statement is repeated 3 times and voila – the values magically swap? Let’s take a closer look. How it works To understand this trick, break the statements into unique values: x1 = x xor y y1 = x1 xor y x2 = x1 xor y1 According to our code, x2 should have y’s original va
Explore this link on the map →saved by
related reading
- Compare-and-swap - Wikipediaen.wikipedia.org
- What is the simplest way to swap each pair of adjoining chars in a string with Python? - Stack Overflowstackoverflow.com
- The Aggregate Magic Algorithmsaggregate.org
- Zenbleedlock.cmpxchg8b.com
- how I think when I think about programming - alice mazalicemaz.com
- Branchless Equivalents of Simple Functions | Harder, Better, Faster, Strongerhbfs.wordpress.com
- Bitmasks - Learn C - Free Interactive C Tutoriallearn-c.org
- A Bunch of Programming Advice I'd Give To Myself 15 Years Ago | Marcus' Blogmbuffett.com
- Efficient Detection of Exchangeable Factors in Factor Graphsarxiv.org
- A fundamental introduction to x86 assembly programmingnayuki.io
- ZX-based quantum obfuscation for dummies – 20[ ] – The blogblog.20squares.xyz
- Lab 1: C Programming and Makefiles - HackMDcs.brown.edu