I am trying to swap the 2 numbers using xor(^). This is what i wrote so far:
float X = 5.5f;
uint Y = 10123456;
X = X ^ Y;
Y = Y ^ X;
X = X ^ Y;
I am trying to swap the 2 numbers using xor(^). This is what i wrote so far:
float X = 5.5f;
uint Y = 10123456;
X = X ^ Y;
Y = Y ^ X;
X = X ^ Y;
How to use xor to swap a float and an uint number?
You Can't Do That™.
XOR is a bitwise operator. Using it on a floating point number requires a serious deep understanding of the way IEEE-754 floating point is represented.
There was a time when programmers might have needed to know all this -- I once handled a requirement to convert IEEE float into DEC float and back -- but now there's hardware and fully-debugged runtime libraries for the purpose. Don't reinvent the flat tire.
Your task requires converting X to a uint
and Y to a float
as the values are swapped.
Doing so requires interpreting the 32 bit floating point number as a 32 bit integer. This typically involves unsafe code like so:
namespace XorSwap
{
class Program
{
unsafe static void Main()
{
float X = 5.5f;
uint* pX = (uint*) &X;
uint Y = 10123456;
*pX = *pX ^ Y;
Y = Y ^ *pX;
*pX = *pX ^ Y;
Console.WriteLine($"X = {X}");
Console.WriteLine($"Y = {Y}");
Console.WriteLine(Math.Abs(X - 1.41859833465e-38) < float.Epsilon); // 10123456 is 1.41859833465e-38 in IEEE 754 hex representation
Console.WriteLine(Y == 0x40b00000); // 5.5f is 0x40b00000 in IEEE 754 hex represenatation
Console.ReadLine();
}
}
}
Note that this is hardly useful. Compilers will notice a typical 3-step-swap operation and generate efficient assembly code. Make your code readable instead of applying premature optimization.