XOR - The Magic Swap
Written by Alex Armstrong   
Article Index
XOR - The Magic Swap
XOR Hashing

The XOR Hash

The XOR "trick" of seeming to be able to store two values in one variable can also be used in other situations. Suppose you have two values A and B and you want to return A when you know B and B when you know A. Then the usual way of doing this is to store both values and return the one you don't know. 

A simpler solution is to store

D= A XOR B

now when you are presented with a value X which is either A or B you return

X XOR D

which is B if X is A and A if X is B.

The best known example of where this can be used is when you want to build a doubly linked list. in this case each node in the list has to hold two references - one to the left node and one to the right node. Usually you would use two variables to store the references. Now you can see that you only need one. 

Pointer= Left XOR Right

Now if you are moving along the linked list from the start to the end you always have the pointer to the Left element - its where you have just come from. So 

Next = Pointer XOR Left

gives you the next node to move to on the right. 

If you are moving along the linked list from end to start then you always have the pointer to the Right element as it is just the node you have just come from. So 

Next = Pointer XOR Right

How worth while this sort of implementation is debatable. It saves one unit of storage per node and many programming languages don't allow this sort of manipulation with a reference - it being too low level. 

It is another fun use of the basic properties of the magic XOR swap. 

Are there more - yes in cryptography but that really is another story.

 

Related Articles

 

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, FacebookGoogle+ or Linkedin,  or sign up for our weekly newsletter.

 

blog comments powered by Disqus

 
Banner


Magic of Merging

The merge sort is an under-appreciated algorithm - yet it is neat, clever and it still has its uses. With the rise of big data, parallel methods and online processing, you can even argue that it is gr [ ... ]



Cache Memory And The Caching Principle

The caching principle is very general but it is best known for its use in speeding up the CPU. We take a look a the basics of cache memory, how it works and what governs how big it needs to be to do i [ ... ]


Other Articles

<ASIN: 0071460519>

<ASIN:0748621679>



 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.