C# structs, byte swapping for conversion from big to little endian using reflection to enumerate members


/ Published in: C#
Save to your folder(s)

<p>This example uses a Swap member to enumerate the struct&#8217;s fields and swap multi-byte fields. It doesn&#8217;t traverse nested structs.</p>

<p>It would be nice if dot.net has something equivalent to &#8216;#pragma endian big&#8217; 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&#8201;&#215;&#8201;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&#8217;t work on structs. It failed quietly.</p>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.