Big-endian and Little-endian and BitConverter

2011-09-30


About Big endian and Little endian explanation, please read the following content from Microsoft:

When designing computers, there are two different architectures for handling memory storage. They are called Big Endian and Little Endian and refer to the order in which the bytes are stored in memory. Windows NT was designed around Little Endian architecture and was not designed to be compatible with Big Endian because most programs are written with some dependency on Little Endian.

These two phrases are derived from "Big End In" and "Little End In." They refer to the way in which memory is stored. On an Intel computer, the little end is stored first. This means a Hex word like 0x1234 is stored in memory as (0x34 0x12). The little end, or lower end, is stored first. The same is true for a four-byte value; for example, 0x12345678 would be stored as (0x78 0x56 0x34 0x12). "Big End In" does this in the reverse fashion, so 0x1234 would be stored as (0x12 0x34) in memory. This is the method used by Motorola computers and can also be used on RISC-based computers. The RISC-based MIPS computers and the DEC Alpha computers are configurable for Big Endian or Little Endian. Windows NT works only in the Little Endian mode on both computers.

Windows NT was designed around Little Endian architecture.

the following 2 images download from here

280px-Little-Endian.svg280px-Big-Endian.svg

For example:

Here is a Hex number: 0x783d4c

We now save it to 3 addresses:

mem[2000] = 0x78,
mem[2001] = 0x3d,
mem[2002] = 0x4c,

mem[] means the address in memory,  this is Big-endian. If reverse, then call Little-endian.

In our Windows platform, the default format is Little-endian. The BitConverter method in C# is also default using Little-endian.

so, if you have a byte[] in C# code like this:

byte[] recBytes;

byte[0] = 0;   //high byte for length
byte[1] = 6;   //low byte for length

Int16 length = System.BitConverter.ToInt16(recBytes, 0);

The length will be 0x0600, but actually the we need length = 0x0006. so in this case the BitConverter can not work correctly.

We can use BitConverter.IsLitteEndian to check the default format firstly, and use reverse if needed:

if (!BitConverter.IsLittleEndian)
    Array.Reverse(recBytes, 0);

However, we have other better solutions:

For little-endian, what you want is:

int length = byte[0] | (byte[1] << 8);

and for big-endian:

int length = (byte[0] << 8) | byte[1];