【发布时间】:2025-12-16 19:35:01
【问题描述】:
我使用以下代码将文件读入结构:
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();
但我注意到任何大于字节的变量,例如 int32、int16 都会反向接收数据。例如,如果文件中的数据是:AA BB CC DD 对应的变量(int32)将是:DD CC BB AA。
我的结构是用属性[StructLayout(LayoutKind.Sequential), Pack = 1]定义的
有人知道为什么以及如何解决它吗?
谢谢!
【问题讨论】:
标签: c# byte endianness