Introduction
I was thinking that what is the purpose of the xor operator in the computer scince language then during playing with the xor operator i found a very amazing thing when i take the xor of the any two decimal binary i found a magecil number which tell me which bits are different in both numbers if they are different then i think by using this number i can exchange the two variables values without using any third variable how first i take the xor of two numbers and save that number in one of them now it is overwritte then i take the xor with the 2nd variable value by which its value become same as the 1st variable before overwrite then take the xor with the first variable with the 2nd updated variable value and get the old 2nd variable value and save in the first variable and finaly both variables value have been exchanged. One thing more the code of this is availabe in java,c++ and c#.
Using the code
using System.Collections.Generic;
using System.Text;
namespace xorapp
{
class application
{
private int bitsdifference(int var1, int var2)
{
return var1 ^ var2; }
public void exchange(ref int var1, ref int var2)
{
var1 = bitsdifference(var1, var2); var2 = var2 ^ var1; var1 = var2 ^ var1; }
}
class Program
{
static void Main(string[] args)
{
application obj = new application();
int a = 6;
int b = 1;
Console.WriteLine("a is before exchanging:\t{0}",a);
Console.WriteLine("b is before exchanging:\t{0}", b);
obj.exchange(ref a, ref b);
Console.WriteLine("a is after exchanging:\t{0}", a);
Console.WriteLine("b is after exchanging:\t{0}", b);
}
}
}
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here