Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big-Endian handling in .Net Core

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];
}
like image 416
Matt DeKrey Avatar asked May 19 '15 13:05

Matt DeKrey


1 Answers

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

like image 88
Alexei Shcherbakov Avatar answered Sep 29 '22 02:09

Alexei Shcherbakov