I have this struct
:
[StructLayout(LayoutKind.Explicit)]
private struct Test
{
[FieldOffset(0)]
public readonly short Foo;
[FieldOffset(2)]
public readonly short Bar;
[FieldOffset(4)]
public readonly short Baz;
}
And the following byte array:
var bytes = new byte[]
{
0x00, 0x01,
0x00, 0x05,
0xFF, 0xFB
};
And I convert my byte array to the structure with the following helper function:
private static T ByteArrayToStructure<T>(byte[] bytes)
where T : struct
{
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
return (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
}
finally
{
handle.Free();
}
}
So I use it as follows:
var test = ByteArrayToStructure<Test>(bytes);
Assert.AreEqual(1, test.Foo);
Assert.AreEqual(5, test.Bar);
Assert.AreEqual(-5, test.Baz);
Now looking at the Asserts we can clearly see what I'm expecting, and this question would be here if the results are not this.
It seems that something is flipping the 2 bytes, so that for the first one it is 0x0100
instead of 0x0001
, for the second one it comes up as 0x0500
instead of 0x0005
, and for the last one it shows up as 0xFBFF
instead of 0xFFFB
.
Is there a way to disable this behavior?