In addition, there is a class called Endian in the Jon Skeet miscutil library that implements conversion methods between an array of bytes and various primitive types, taking into account the statement.
For your question, usage would be something like this:
// Input data byte[] tab = new byte[32]; // Pick the appropriate endianness Endian endian = Endian.Little; // Use the appropriate endian to convert int a = endian.ToInt32(tab, 0); int b = endian.ToInt32(tab, 4); int c = endian.ToInt32(tab, 8); int d = endian.ToInt32(tab, 16); ...
A simplified version of the Endian class will look something like this:
public abstract class Endian { public short ToInt16(byte[] value, int startIndex) { return unchecked((short)FromBytes(value, startIndex, 2)); } public int ToInt32(byte[] value, int startIndex) { return unchecked((int)FromBytes(value, startIndex, 4)); } public long ToInt64(byte[] value, int startIndex) { return FromBytes(value, startIndex, 8); }
And then the FromBytes abstract method FromBytes implemented differently for each endian type.
public class BigEndian : Endian { protected override long FromBytes(byte[] buffer, int startIndex, int len) { long ret = 0; for (int i=0; i < len; i++) { ret = unchecked((ret << 8) | buffer[startIndex+i]); } return ret; } } public class LittleEndian : Endian { protected override long FromBytes(byte[] buffer, int startIndex, int len) { long ret = 0; for (int i=0; i < len; i++) { ret = unchecked((ret << 8) | buffer[startIndex+len-1-i]); } return ret; } }
Groo
source share