Saturday, 30 May 2015

XOR : The Exclusive OR



public class XORBasics {
public static void main(String[] args) {
/**
* What is XOR ?

* XOR is an binary operator which when applied on two numbers, it returns 0 in case both the numbers are same


*  0 ^ 0 = 0 (XOR for same bits results in 0)
*  0 ^ 1 = 1 
*  1 ^ 0 = 1
*  1 ^ 1 = 0 (XOR for same bits results in 0)

* Lets have two numbers a=3 and b=4. expressing them in binary and then applying the XOR operation on them below.
*  
*  Number     Binary   Decimal 
*     a                011        3
*     b                100        4
*     c                111        7
*     
*  As per property of XOR a^b is same as b^a
*  Also an interesting property of XOR is 
*  if c = a^b then b = a^c and a = b^c.
*  
*  
*                               
*/
int a = 3;
int b = 4;
int c = a^b;
System.out.println("a is "+a);
System.out.println("b is "+b);
System.out.println("c is "+c);
System.out.println("a^c "+ (a^c));
System.out.println("b^c is "+(b^c));
System.out.println("is a^c equals c^a ? "+((a^c) == (c^a)));
/**
* Swapping two numbers using XOR operator. In this we do not need the third variable.
* if x = 10 and y = 20;
* then performing below 3 steps swaps the numbers
* STEP1. y = x^y;
* STEP2. x = x^y;
* STEP3. y = x^y;

* Lets see how it works
* STEP1. lets take a variable z = x^y. so y is assigned value of z, i.e new value of y is z. 
* STEP2. x = x^(new value of y) = x^z. So x is assigned a new value i.e x^z which from previous example we know would be original value of y.
*   So new value of x is now y
*      STEP3. y = (new value of x)^(new value of y) = y^z. which we know should be original value of x

*/
int x = 10;
int y = 20;
y = x^y;
x = x^y;
y = x^y;
System.out.println("new value of x is "+ x);
System.out.println("new value of y is "+ y);
}
}