title: Marshalling a big-endian byte collection into a struct in order to pull out values
body: <p>There is an insightful question about <a href="https://stackoverflow.com/questions/2871/reading-a-c-c-data-structure-in-c-from-a-byte-array">reading a C/C++ data structure in C# from a byte array</a>, 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)?</p>
  
  <p>(Note, reversing the array of bytes will <strong>not</strong> work - each value's bytes must be reversed, which does not give you the same collection as reversing all of the bytes.)</p>
  
  <p>This should summarize what I'm looking for (LE=LittleEndian, BE=BigEndian):</p>
  
  <pre><code>void Main()
  {
      var leBytes = new byte[] {1, 0, 2, 0};
      var beBytes = new byte[] {0, 1, 0, 2};
      Foo fooLe = ByteArrayToStructure&lt;Foo&gt;(leBytes);
      Foo fooBe = ByteArrayToStructureBigEndian&lt;Foo&gt;(beBytes);
      Assert.AreEqual(fooLe, fooBe);
  }
  
  [StructLayout(LayoutKind.Explicit, Size=4)]
  public struct Foo  {
      [FieldOffset(0)] 
      public ushort firstUshort;
      [FieldOffset(2)] 
      public ushort secondUshort;
  }
  
  T ByteArrayToStructure&lt;T&gt;(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&lt;T&gt;(byte[] bytes) where T: struct 
  {
      ???
  }
  </code></pre>
  
  <p>Other helpful links:</p>
  
  <p><a href="http://blogs.msdn.com/jeremykuhne/archive/2005/07/19/440264.aspx" rel="nofollow noreferrer">Byte of a struct and onto endian concerns</a></p>
  
  <p><a href="http://blogs.msdn.com/jeremykuhne/archive/2005/07/21/441247.aspx" rel="nofollow noreferrer">A little more on bytes and endianness (byte order)</a></p>
  
  <p><a href="http://www.builderau.com.au/architect/webservices/soa/Read-binary-files-more-efficiently-using-C-/0,339024590,320277904,00.htm" rel="nofollow noreferrer">Read binary files more efficiently using C#</a></p>
  
  <p><a href="http://blogs.msdn.com/ericgu/archive/2004/04/13/112297.aspx" rel="nofollow noreferrer">Unsafe and reading from files</a></p>
  
  <p><a href="http://www.mono-project.com/Mono_DataConvert" rel="nofollow noreferrer">Mono's contribution to the issue</a></p>
  
  <p><a href="http://www.developerfusion.com/article/84519/mastering-structs-in-c/" rel="nofollow noreferrer">Mastering C# structs</a></p>