Let’s say we have a binary file that contains 2 bytes that form an integer, in reverse.
So for example, the bytes show like this: (hexadecimal)
EB 03 00 00
Which should be interpreted as this:
00 00 03 EB
Which C# should be able to input as decimal 1003. Is this possible if you have the EB and 03 bytes already in memory in 2 different variables? Is there some math I can apply here to form decimal 1003 from the numbers 235 and 3? Or should I do it completely different?
Thanks in advance!
What you talk about is called Endianness, in particular Little Endian format.
In C#, it’s probably easiest to use a
BinaryReaderorBinaryWriterto read from binary files which wrap the correct conversion of the byte order.The following sample shows how to use a
BinaryReaderto get the correct integer interpretation of a number in Little Endian format: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
BitConverterclass. In the sample above you could do the following to cope with Big Endian (on a Little Endian platform):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):
Update
The MiscUtil library provides a binary reader/writer class that can be configured for a specific Endianness: