在C#中读取大端数据的有效方法

Hos*_*Rad 10 c# endianness binaryreader

我使用以下代码来阅读BigEndian信息,BinaryReader但我不确定它是否是有效的方法.有没有更好的解决方案?

这是我的代码:

// 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);
Run Code Online (Sandbox Code Playgroud)

Cod*_*aos 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];
}
Run Code Online (Sandbox Code Playgroud)

您还可以考虑一次读取超过4个字节.