Really machine independent binary files with c#

When it first comes to really portable programs which run on several machine architectures (like PC and PocketPC) you will notice that 'managed' is NOT always 'managed'.
The problem is that different processor architectures use different Endianness, meaning the memory is organized in a different way.

Their are two popular endianness:

  • Big Endian:
    Meaning the most significant byte comes first
  • Little Endian:
    Meaning the least significant byte comes first

As you can imagine BigEndian and LittleEndian is not compatible to each other ;-)
This means, when transfering or saving bytes always chose one, fixed endianness.

This can be achived by implementing a low level ByteHelper (class is attached) which performs the basic write operations and converts to the target format if
neccessary.

The key parts are the following:

  • PackBits converts the byte array to the machine independent format
  • UnpackBits converts the byte array to the machine version
private static void PackBits(byte[] target, int offset, byte[] src_bits, int length)
{
Array.Copy(src_bits, 0, target, offset, length);
 if (BitConverter.IsLittleEndian)
 Array.Reverse(target, offset, length);
 }
 private static byte[] UnpackBits(byte[] src_bits, int offset, int length)
 {
byte[] cpu_bits = new byte[length];
 Array.Copy(src_bits, offset, cpu_bits, 0, length);
 if (BitConverter.IsLittleEndian)
 Array.Reverse(cpu_bits, 0, length);
return cpu_bits;
}

Check out the ByteHelper at https://github.com/deveck/Deveck.Utils/blob/master/ByteUtils/ByteHelpers.cs

It can also write and read primitive types like Int32 (PackedInt32), decimal, string,...