energ1ser
energ1ser

Reputation: 2873

How to duplicate Delphi's swap function in c#

I am trying to write a swap function in C# to mimic the one in Delphi. According to the documentation the one in Delphi will do the following:

Below is the code I have.

int number = 17665024;
var hi = (byte)(number >> 24);
var lo = (byte)(number & 0xff);
return (number & 0x00FFFF00) + (lo & 0xFF000000) + (hi & 0x000000FF);

Some numbers seem to return what I expect, but most do not.

// Value in        // Expected         // Actual
17665024           887809              887809
5376               21                  5376
-30720             136                 16746751
3328               13                  3328

It's probably a fairly obvious mistake to most, but I haven't dealt with bitwise shift operators much and I cannot seem to work out what I have done wrong.

Thanks in advance.

Upvotes: 1

Views: 244

Answers (1)

drf
drf

Reputation: 8699

In C#, the data types short and int correspond to integral data types of 2 bytes and 4 bytes, respectively. The algorithm above applies to int (4 bytes).

This algorithm contains an error: (lo & 0xFF000000) will always return 0 because lo is a byte. What you probably intended was lo << 24, which shifts lo 24 bytes to the left.

For an int data type, the proper function then becomes:

    int SwapInt(int number)
    {
        var hi = (byte)(number >> 24);
        var lo = (byte)(number & 0xff);
        return ((number & 0xffff00) | (lo << 24) | hi);
    }

For a short data type, the middle term disappears and we are left with simply:

    short SwapShort(short number)
    {
        var hi = (byte)(number >> 8);
        var lo = (byte)(number & 0xff);
        return (short)((lo << 8) | hi);
    }

Then Swap((short)5376) returns the expected value of 21. Note that Swap(5376) will use the default int datatype for 5376, which returns 5376. To treat integers that can be wholly expressed in two bytes as short, you can run:

   int Swap(int n)
   {
        if (n >= Short.MinValue && n <= Short.MaxValue)
              return SwapShort((short)n);
        else
              return SwapInt(n);
   }

Upvotes: 3

Related Questions