I saw a neat way to swap 2 variables using XOR lately and decided to try that in c# with strings, and though I managed to do that I'm a little worried that I have to cast int into byte after the XOR operation. Here's the code:
var string1 = Encoding.ASCII.GetBytes("Hello world1!");
var string2 = Encoding.ASCII.GetBytes("Hello world2!");
for (var i = 0; i < string1.Length; i++)
{
string1[i] = (byte)(string1[i] ^ string2[i]);
}
for (var i = 0; i < string2.Length; i++)
{
string2[i] = (byte)(string1[i] ^ string2[i]);
}
for (var i = 0; i < string1.Length; i++)
{
string1[i] = (byte)(string2[i] ^ string1[i]);
}
Console.WriteLine(Encoding.ASCII.GetString(string1));
Console.WriteLine(Encoding.ASCII.GetString(string2));
Is there any better way of doing this? And while we are at it, what actually happens when you cast primitives in C#? Is there any new memory being allocated for it?
With the introduction of tuples in C#, the xor
trick is actually no longer as neat as it used to be:
var string1 = Encoding.ASCII.GetBytes("Hello world1!");
var string2 = Encoding.ASCII.GetBytes("Hello world2!");
(string1, string2) = (string2, string1);
Console.WriteLine(Encoding.ASCII.GetString(string1));
Console.WriteLine(Encoding.ASCII.GetString(string2));
The tuple syntax is explained here.