11

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);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116

3 Answers3

12

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.

Joey
  • 344,408
  • 85
  • 689
  • 683
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • thanks It's very interesting but to be sure that I got the idea correctly, can you explain how we can read more than 4 bytes. – Hossein Narimani Rad Jan 18 '13 at 15:07
  • 1
    Just call `ReadBytes` with a larger length, and then use different `i`s to read integers at different positions in the array. But that's an optimization you should only take after benchmarking. – CodesInChaos Jan 18 '13 at 15:31
  • Yes, I've used something like this for some of my projects (albeit not in C#). But I had expected BinaryReader/Writer to have endian control built in, which would make it much simpler. – Stewart Mar 05 '15 at 11:18
3

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

byte[] buffer = ...;

BinaryPrimitives.ReadInt32BigEndian(buffer.AsSpan());

Documentation

Implementation

cube45
  • 3,429
  • 2
  • 24
  • 35
1

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

Matt Burland
  • 44,552
  • 18
  • 99
  • 171