0

I read a file into a struct using this code:

StructType aStruct;
int count = Marshal.SizeOf(typeof(StructType));
byte[] readBuffer = new byte[count];
BinaryReader reader = new BinaryReader(stream);
readBuffer = reader.ReadBytes(count);
GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);
aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType));
handle.Free();

But I noticed that any variable bigger then byte, like int32, int16 receives the data backwards. For example, if in the file the data was: AA BB CC DD the corresponding variable(int32) will be : DD CC BB AA.

My struct is defined with the attribute [StructLayout(LayoutKind.Sequential), Pack = 1]

Anyone knows why and how to solve it?

Thank you!

123456
  • 113
  • 8

1 Answers1

0

That happens if the file uses the big-endian byte order, but of course the data members of the struct are little-endian and there is nothing you can do about that. There is no layout specifier that changes the endianness of struct fields, it's a property of the platform. There are some options to deal with big-endian files:

  • If you can change the file format, that would an easy solution. That will make both loading and saving the file easier.
  • Read the struct with its fields "the wrong way around", then go over all the fields and flip them with eg some bit-manipulation, like this. It is relatively easy to accidentally leave a field in the wrong order.
  • Give up on reading the easy way with a straight copy, instead read the fields one by one, each in big-endian for example using one of these options.
harold
  • 61,398
  • 6
  • 86
  • 164