# Posted By

pckujawa on 04/20/10

# Statistics

Viewed 1900 times
Favorited by 0 user(s)

# Byte Swapping Structs For Conversion From Big To Little Endian (Byte Order)

/ Published in: C#
`public void Main(){	var beBytes = new byte[] {		0x80, 		0x80, 		0x80, 		0x80, 		0x80,0, 		0x80,0, 		0x80,0,0,0, 		0x80,0,0,0,		0x80,0,0,0,0,0,0,0, 		0x80,0,0,0,0,0,0,0,//		0x3F,0x80,0,0,//		0x3F,0xF0,0,0,0,0,0,0,//		0x30,0,0,0,0,0,0,0,0,0,		0x54,0x65,0x73,0x74,0x69,0x6E,0x67,0,0,0	};	var leBytes = new byte[] {		0x80, 		0x80, 		0x80, 		0x80, 		0,0x80,		0,0x80, 		0,0,0,0x80,		0,0,0,0x80, 		0,0,0,0,0,0,0,0x80, 		0,0,0,0,0,0,0,0x80, //		0,0,0x80,0x3F,//		0,0,0,0,0,0,0xF0,0x3F,//		0x30,0,0,0,0,0,0,0,0,0,		0x54,0x65,0x73,0x74,0x69,0x6E,0x67,0,0,0	};	Foo fooLe = ByteArrayToStructure<Foo>(leBytes).Dump("LE");	Foo fooBe = ByteArrayToStructureBigEndian<Foo>(beBytes, 		"bbbbsSiIlL"//		+ "fd"				+"9bb").Dump("BE");//	Assert.AreEqual(fooLe, fooBe);} [StructLayout(LayoutKind.Sequential, Pack = 1)]public struct Foo  {	public byte b1;	public byte b2;	public byte b3;	public byte b4;	public short s;	public ushort S;	public int i;	public uint I;	public long l;	public ulong L;//	public float f;//	public double d;	[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]	public string MyString;} T ByteArrayToStructure<T>(byte[] bytes) where T: struct {	GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);	T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),typeof(T));	handle.Free();	return stuff;} T ByteArrayToStructureBigEndian<T>(byte[] bytes, string description) where T: struct {	byte[] buffer = bytes;	IList unpacked = DataConverter.Unpack("^"+description, buffer, 0).Dump("unpacked");	buffer = DataConverter.PackEnumerable("!"+description, unpacked).Dump("packed");	return ByteArrayToStructure<T>(buffer);}`