Remember the endians!
For those of you that deal with bytes on a protocol level, I’ve discovered an easy solution for dealing with those endian issues. Some of you may know that when dumping data directly from memory as byte[] arrays will give you different results depending on the source’s computer architecture. As an example, a Motorola ColdFire board (LittleEndian) will dump the data differently than say an i386 (BigEndian) based processor. In a nutshell, this means that the byte[] arrays from the ColdFire board will be in reverse order than that of an i386 based microcontroller byte[] array. Obviously when processing this data you’ll run into huge problems if you don’t convert your byte[] arrays!
The simplest way to do this is to use the BitConverter class library in .NET as shown below (Correct me if I’m wrong!). The BitConverter class allows you to check for LittleEndians to allow you to reverse the byte[]array which will then be a BigEndian. This example is returning a 32bit integer from a byte[] array at a given index in the byte[] array. Remember, parsing data such as UDP network packets is normally done using byte[] arrays.
private static Int32 ToInt32(byte[] value, int startIndex) { byte[] data = new byte[4]; Array.Copy(value, startIndex, data, 0, 4); if (BitConverter.IsLittleEndian) Array.Reverse(data); return BitConverter.ToInt32(data, 0); }
