我使用以下代码使用BinaryReader
读取BigEndian信息,但我不确定它是否是有效的方法。有没有更好的解决方案?
这是我的代码:
// some code to initialize the stream value
// set the length value to the Int32 size
BinaryReader reader =new BinaryReader(stream);
byte[] bytes = reader.ReadBytes(length);
Array.Reverse(bytes);
int result = System.BitConverter.ToInt32(temp, 0);
答案 0 :(得分:12)
BitConverter.ToInt32
首先不是很快。我只是使用
public static int ToInt32BigEndian(byte[] buf, int i)
{
return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3];
}
您还可以考虑一次读取超过4个字节。
答案 1 :(得分:1)
你可以使用IPAddress.NetworkToHostOrder,但我不知道它是否真的更有效率。你必须对它进行分析。
答案 2 :(得分:1)
截至2019年(实际上,自.net core 2.1起),
byte[] buffer = ...;
BinaryPrimitives.ReadInt32BigEndian(buffer.AsSpan());