What you talk about is called Endianness, in particular Little Endian format.
In C#, it's probably easiest to use a BinaryReader
or BinaryWriter
to read from binary files which wrap the correct conversion of the byte order.
The following sample shows how to use a BinaryReader
to get the correct integer interpretation of a number in Little Endian format:
using System.IO;
class EndiannessSample
{
static void Main(string[] args)
{
using (MemoryStream ms = new MemoryStream())
{
// write bytes in little-endian format
ms.WriteByte(0xEB);
ms.WriteByte(0x03);
ms.WriteByte(0x00);
ms.WriteByte(0x00);
ms.Position = 0;
using (BinaryReader reader = new BinaryReader(ms))
{
int i = reader.ReadInt32(); // decimal value of i is 1003
}
}
}
}
Little endian is the standard on Intel (and Windows) platforms. In case you have to deal with data in Big Endian format (e.g. when importing files created on an old Macintosh) there is no direct support within .NET. You can write a simple utility function for converting endianness using the BitConverter
class. In the sample above you could do the following to cope with Big Endian (on a Little Endian platform):
using (MemoryStream ms = new MemoryStream())
{
// write bytes in big-endian format
ms.WriteByte(0x00);
ms.WriteByte(0x00);
ms.WriteByte(0x03);
ms.WriteByte(0xEB);
ms.Position = 0;
using (BinaryReader reader = new BinaryReader(ms))
{
byte[] temp = reader.ReadBytes(4);
if (BitConverter.IsLittleEndian)
{
// reverse the byte order only if we are on a little-endian system,
// because the BitConverter is aware of the endianness of the system
//
Array.Reverse(temp);
}
int i = BitConverter.ToInt32(temp, 0);
}
}
LukeH provided a link that further discusses problems related to Endianness, e.g. when targeting Xbox 360 (which happens to be a Big Endian platform):
One Little, Two Little, Three Little Endian... 0x0A Big Endian Bugs
Update
The MiscUtil library provides a binary reader/writer class that can be configured for a specific Endianness:
MiscUtil.IO.EndianBinary{Writer/Reader}