/ Published in: C#
<p>This example uses a Swap member to enumerate the struct’s fields and swap multi-byte fields. It doesn’t traverse nested structs.</p>
<p>It would be nice if dot.net has something equivalent to ‘#pragma endian big’ as seen in some compilers. There might be a way to leverage marshaling to automatically endianize multi-byte values.</p>
<p>This example uses:
* System.Net.IPAddress.NetworkToHostOrder for byte swapping
* unchecked() to convert a value of, say, 0 × 87654321 to a Int32 without a runtime error
* foreach (System.Reflection.FieldInfo field in typeof(MyStruct).GetFields()) to enumerate structure members
* TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType()); to get the underlying type enumeration (typeof of verbose).
* SetValue and GetValue to access struct members.
* Boxed object of struct - this was necessary only because SetValue didn’t work on structs. It failed quietly.</p>
<p>It would be nice if dot.net has something equivalent to ‘#pragma endian big’ as seen in some compilers. There might be a way to leverage marshaling to automatically endianize multi-byte values.</p>
<p>This example uses:
* System.Net.IPAddress.NetworkToHostOrder for byte swapping
* unchecked() to convert a value of, say, 0 × 87654321 to a Int32 without a runtime error
* foreach (System.Reflection.FieldInfo field in typeof(MyStruct).GetFields()) to enumerate structure members
* TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType()); to get the underlying type enumeration (typeof of verbose).
* SetValue and GetValue to access struct members.
* Boxed object of struct - this was necessary only because SetValue didn’t work on structs. It failed quietly.</p>