[Study] Understanding XOR operation

XOR and minus seems to be about the same in concept, because, as if “A-B” means “difference between A and B”, A^B also means “bitwise difference between A and B”.

Let’s see following two SWAP algorithm. (Analysing following alogrithm will be helpful to understand difference of concept between ‘A-B’ and ‘A^B’).

add swap
*x = *x + *y;
*y = *x – *y;
*x = *x – *y;

xor swap
*x ^= *y;
*y ^= *x;
*x ^= *y;

We should focus on that both of ‘-‘ and XOR are operation to get “difference”.
(‘-‘ is difference of number and XOR is bitwise difference. But, those are all “difference”!)
So, we can implement swap operation with both ‘-‘ and “XOR”.

Here is conceptual description of XOR swap.
*x ^= *y; “Store difference of ‘original x’ and ‘original y'”
*y ^= *x; “We know difference of ‘original x’ and ‘original y'(x). So, we can get ‘original x’ with ‘original y’ and store it into ‘y’.”
*x ^= *y; “We know difference of ‘original x’ and ‘original y'(x), and ‘orignal x'(y). So, we can get ‘original y’ and store it into ‘x’.”

Understanding something is “Understanding it’s basic concept”. It’s very important.!!

So, someone who understands XOR, should be able to infer “swap with XOR” at the moment of knowing about “swap with ‘+/-‘”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s