0

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;
Christos
  • 19
  • 6
  • 5
    You can't. xor is an *integer* operator. It doesn't apply to floating point numbers. – Dennis_E May 18 '21 at 11:13
  • 2
    If this is for homework: You can't. Otherwise: You shouldn't waste your time with such a useless goal.. – TaW May 18 '21 at 11:21
  • 4
    Compilers are written to notice tmp=x, x=y, y=tmp constructs and use faster methods than an xor swap, so although it was useful once upon a time, the xor swap is now mostly redundant. – Andrew Morton May 18 '21 at 11:22

2 Answers2

3

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.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
2

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.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222