读取网络字节流时候,使用BinaryReader的ReadInt32()方法时候发生了预期外的结果,查阅了微软文档发现是小端( )模式问题,可以通过System.Net.IPAddress.HostToNetworkOrder或BinaryPrimitives.ReadInt32BigEndian 方式来解决
以下示例代码,提供参考
csharp
var sendNu = 1102;
var sendBuf = BitConverter.GetBytes(sendNu);
if (BitConverter.IsLittleEndian)
{
var sendBufByBig = sendBuf.Reverse().ToArray();
}
var bufByLittle = new byte[] { 77, 4, 0, 0 };
var bufByBig = bufByLittle.Reverse().ToArray();
var originalNu = BitConverter.ToInt32(bufByBig.Reverse().ToArray());
using var fs = new MemoryStream(bufByLittle);
var binReader = new BinaryReader(fs);
var orgVal = binReader.ReadUInt32();
var orgVal1 = BinaryPrimitives.ReadInt32BigEndian(bufByBig);