6

Is there a BitConverter or other class that supports .Net Core that I can read integers and other values as having Big Endian encoding?

I don't feel good about needing to write a set of helper methods:

int GetBigEndianIntegerFromByteArray(byte[] data, int startIndex) {
    return (data[startIndex] << 24)
         | (data[startIndex + 1] << 16)
         | (data[startIndex + 2] << 8)
         | data[startIndex + 3];
}
phuclv
  • 37,963
  • 15
  • 156
  • 475
Matt DeKrey
  • 11,582
  • 5
  • 54
  • 69

3 Answers3

9

Since .NET Core 2.1 there is a unified API for this in static class System.Buffers.Binary.BinaryPrimitives

It contains API for ReadOnlySpan and direct inverse endianness for primitive types (short/ushort,int/uint,long/ulong)

private void GetBigEndianIntegerFromByteArray(ReadOnlySpan<byte> span,int offset)
{
    return BinaryPrimitives.ReadInt32BigEndian(span.Slice(offset));
}

System.Buffers.Binary.BinaryPrimitives class is a part of .NET Core 2.1 and no NuGet packages are needed

Also this class contains Try... methods

Alexei Shcherbakov
  • 1,125
  • 13
  • 10
0

The BitConverter class with a ToInt32() method exists in the System.Runtime.Extensions package.

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
  • 2
    Yeah, unfortunately, as the source makes plain, this only works for the "endianess" of the system it's built in; it won't always be Big Endian or Little Endian. This works fine if you're reading and writing with the same application on the same system, but as soon as you change dnx environments, you can't trust the save files. – Matt DeKrey Sep 08 '15 at 23:04
0
using System;
using System.Linq;

int GetBigEndianIntegerFromByteArray(byte[] data, int startIndex) 
{
    if (BitConverter.IsLittleEndian)
    {
        return BitConverter.ToInt32(data.Skip(startIndex).Take(sizeof(int)).Reverse().ToArray(), 0);
    }

    return BitConverter.ToInt32(data, startIndex);
}
moien
  • 999
  • 11
  • 26
  • Another very readable way to do just Int32, though this one has the disadvantage of using more memory and likely slower. At this point, I'd really like to see a .Net Standard library (1.0, since BitConverter is available there) whether produced by Microsoft or other OSS library that takes on this problem set. – Matt DeKrey Aug 20 '18 at 11:35
  • @MattDeKrey, I agree. What about IPAddress.HostToNetworkOrder ? – moien Aug 20 '18 at 18:34
  • Unfortunately, "Network Order" is always "the most significant byte first". (According to https://learn.microsoft.com/de-de/dotnet/api/system.net.ipaddress.networktohostorder) - otherwise, that would be a good fit. – Matt DeKrey Aug 21 '18 at 11:57