Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to read big endian data in C#

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);
like image 699
Hossein Narimani Rad Avatar asked Jan 18 '13 14:01

Hossein Narimani Rad


3 Answers

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.

like image 132
CodesInChaos Avatar answered Nov 09 '22 19:11

CodesInChaos


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

byte[] buffer = ...;

BinaryPrimitives.ReadInt32BigEndian(buffer.AsSpan());

Documentation

Implementation

like image 43
cube45 Avatar answered Nov 09 '22 19:11

cube45


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

like image 20
Matt Burland Avatar answered Nov 09 '22 21:11

Matt Burland