C# – Endian Swap

In 1726, there were tensions between Lilliput and Blefuscu, the problem being soft-boiled eggs. The inhabitants of Lilliput crack open their eggs at the small end, while the inhabitants of Blefuscu crack open theirs at the big end.

In 2010, while writing a Midi file parser in C#, I needed the ability to swap the endian of the data, since Midi files are stored as Big Endian, converting them into Little Endian.

I would have thought there would be some function within the BitConverter class to be able to swap, but there didn’t appear to be, so I wrote my own.

Since swapping endian is just reversing the byte order, the simplest method would be to get the bytes of a number, and reverse the array, then reconstruct the number using the reversed bytes.

//
//
using System;
 
//
//
namespace Midi
{
class Endian
{
	//
	public static UInt16 SwapUInt16( UInt16 inValue )
	{
		byte[] byteArray = BitConverter.GetBytes(inValue);
		Array.Reverse(byteArray);
		return BitConverter.ToUInt16(byteArray,0);
	}
 
	//
	public static UInt32 SwapUInt32( UInt32 inValue )
	{
		byte[] byteArray = BitConverter.GetBytes(inValue);
		Array.Reverse(byteArray);
		return BitConverter.ToUInt32(byteArray,0);
	}
}
}

 

But this method is slower than just using a bitshift.

//
//
using System;
 
//
//
namespace Midi
{
class Endian
{
	//
	public static UInt16 SwapUInt16( UInt16 inValue )
	{
		return (UInt16)( ((inValue & 0xff00) >> 8) |
				 ((inValue & 0x00ff) << 8) );
	}
 
	//
	public static UInt32 SwapUInt32( UInt32 inValue )
	{
		return (UInt32)( ((inValue & 0xff000000) >> 24) |
				 ((inValue & 0x00ff0000) >> 8) |
				 ((inValue & 0x0000ff00) << 8) |
				 ((inValue & 0x000000ff) << 24) );
	}
}
}

 

Since any the there are only 16 bit and 32 bit numbers in the Midi file format, and anything larger is of Variable Length Quantity, these are the only two required.