Efficient way to read big endian data in C#

后端 未结 3 1665
Happy的楠姐
Happy的楠姐 2020-12-30 07:50

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

相关标签:
3条回答
  • 2020-12-30 08:11

    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.

    0 讨论(0)
  • 2020-12-30 08:26

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

    byte[] buffer = ...;
    
    BinaryPrimitives.ReadInt32BigEndian(buffer.AsSpan());
    

    Documentation

    Implementation

    0 讨论(0)
  • 2020-12-30 08:35

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

    0 讨论(0)
提交回复
热议问题