Marshalling a big-endian byte collection into a struct in order to pull out values
- by Pat
There is an insightful question about reading a C/C++ data structure in C# from a byte array, but I cannot get the code to work for my collection of big-endian (network byte order) bytes. (EDIT: Note that my real struct has more than just one field.) Is there a way to marshal the bytes into a big-endian version of the structure and then pull out the values in the endianness of the framework (that of the host, which is usually little-endian)?
This should summarize what I'm looking for (LE=LittleEndian, BE=BigEndian):
void Main()
{
var leBytes = new byte[] {1, 0};
var beBytes = new byte[] {0, 1};
Foo fooLe = ByteArrayToStructure<Foo>(leBytes);
Foo fooBe = ByteArrayToStructureBigEndian<Foo>(beBytes);
Assert.AreEqual(fooLe, fooBe);
}
[StructLayout(LayoutKind.Explicit, Size=2)]
public struct Foo {
[FieldOffset(0)]
public ushort firstUshort;
}
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) where T: struct
{
???
}