karolyzz
karolyzz

Reputation: 510

Is this a legit way to swap endianness?

As the title says, I have UInt16 that is read using BinaryReader from a file. The file contains hex in order "0x0102" whereas after reading it is in reverse. Is this legit? I heard that BitConverter works according to how the endianness is set in the pc, but I use it twice, so it seems like everything should work fine?

public static UInt16 EndiannessSwap(UInt16 data)
{
   var step1 = BitConverter.GetBytes(data);
   var step2 = step1.Reverse().ToArray();
   var step3 = BitConverter.ToUInt16(step2, 0);
   return step3;
}

Upvotes: 1

Views: 109

Answers (2)

Wazner
Wazner

Reputation: 3102

Yes, this code will work and will be portable, although not very efficient. You are right that BitConverter works according to the endianness of the machine, but because you're using it's output as input this cancels out.

A more efficient way of swapping endianness would be using bit shifts. Seeing as an UInt16 only consists of 2x byte (8-bits) we can easily swap it as follows:

public static UInt16 EndiannessSwap(UInt16 data)
{
   return unchecked((ushort)((data << 8) | (data >> 8)));
}

Upvotes: 5

richej
richej

Reputation: 834

I am using a very similar solution without problems:

public static UInt16 EndiannessSwap(UInt16 data)
{
    var intAsBytes = BitConverter.GetBytes(data);
    Array.Reverse(intAsBytes);
    return BitConverter.ToUInt16(intAsBytes, 0);
}

Upvotes: 1

Related Questions