Efficient way to read big endian data in C#

断了今生、忘了曾经 提交于 2019-12-18 13:13:14

问题


I use the following code to read BigEndian information using BinaryReader but I'm not sure if it is the efficient way of doing it. Is there any better solution?

Here is my code:

// 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);

回答1:


BitConverter.ToInt32 isn't very fast in the first place. I'd simply use

public static int ToInt32BigEndian(byte[] buf, int i)
{
  return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3];
}

You could also consider reading more than 4 bytes at a time.




回答2:


You could use IPAddress.NetworkToHostOrder, but I have no idea if it's actually more efficient. You'd have to profile it.




回答3:


As of 2019 (in fact, since .net core 2.1), there is now

byte[] buffer = ...;

BinaryPrimitives.ReadInt32BigEndian(buffer.AsSpan());

Documentation

Implementation



来源:https://stackoverflow.com/questions/14401270/efficient-way-to-read-big-endian-data-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!