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


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

See the URL for my question and answer on StackOverflow.


Copy this code and paste it in your HTML
  1. public void Main()
  2. {
  3. var beBytes = new byte[] {
  4. 0x80,
  5. 0x80,
  6. 0x80,
  7. 0x80,
  8. 0x80,0,
  9. 0x80,0,
  10. 0x80,0,0,0,
  11. 0x80,0,0,0,
  12. 0x80,0,0,0,0,0,0,0,
  13. 0x80,0,0,0,0,0,0,0,
  14. // 0x3F,0x80,0,0,
  15. // 0x3F,0xF0,0,0,0,0,0,0,
  16. // 0x30,0,0,0,0,0,0,0,0,0,
  17. 0x54,0x65,0x73,0x74,0x69,0x6E,0x67,0,0,0
  18. };
  19. var leBytes = new byte[] {
  20. 0x80,
  21. 0x80,
  22. 0x80,
  23. 0x80,
  24. 0,0x80,
  25. 0,0x80,
  26. 0,0,0,0x80,
  27. 0,0,0,0x80,
  28. 0,0,0,0,0,0,0,0x80,
  29. 0,0,0,0,0,0,0,0x80,
  30. // 0,0,0x80,0x3F,
  31. // 0,0,0,0,0,0,0xF0,0x3F,
  32. // 0x30,0,0,0,0,0,0,0,0,0,
  33. 0x54,0x65,0x73,0x74,0x69,0x6E,0x67,0,0,0
  34. };
  35. Foo fooLe = ByteArrayToStructure<Foo>(leBytes).Dump("LE");
  36. Foo fooBe = ByteArrayToStructureBigEndian<Foo>(beBytes,
  37. "bbbbsSiIlL"
  38. // + "fd"
  39. +"9bb").Dump("BE");
  40. // Assert.AreEqual(fooLe, fooBe);
  41. }
  42.  
  43. [StructLayout(LayoutKind.Sequential, Pack = 1)]
  44. public struct Foo {
  45. public byte b1;
  46. public byte b2;
  47. public byte b3;
  48. public byte b4;
  49. public short s;
  50. public ushort S;
  51. public int i;
  52. public uint I;
  53. public long l;
  54. public ulong L;
  55. // public float f;
  56. // public double d;
  57. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
  58. public string MyString;
  59. }
  60.  
  61. T ByteArrayToStructure<T>(byte[] bytes) where T: struct
  62. {
  63. GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
  64. T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(),typeof(T));
  65. handle.Free();
  66. return stuff;
  67. }
  68.  
  69. T ByteArrayToStructureBigEndian<T>(byte[] bytes, string description) where T: struct
  70. {
  71. byte[] buffer = bytes;
  72. IList unpacked = DataConverter.Unpack("^"+description, buffer, 0).Dump("unpacked");
  73. buffer = DataConverter.PackEnumerable("!"+description, unpacked).Dump("packed");
  74. return ByteArrayToStructure<T>(buffer);
  75. }

URL: http://stackoverflow.com/questions/2480116/marshalling-a-big-endian-byte-collection-into-a-struct-in-order-to-pull-out-value/2678472#2678472

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.