Big-Endian handling in .Net Core
Asked Answered
V

3

7

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];
}
Vinegary answered 19/5, 2015 at 13:5 Comment(0)
I
11

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

Inly answered 24/10, 2018 at 12:11 Comment(1)
And, even better, this is .Net Standard! Thanks for running into this old question!Vinegary
B
0

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

Betthezel answered 8/9, 2015 at 18:14 Comment(1)
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.Vinegary
B
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);
}
Bret answered 19/8, 2018 at 11:37 Comment(3)
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.Vinegary
@MattDeKrey, I agree. What about IPAddress.HostToNetworkOrder ?Bret
Unfortunately, "Network Order" is always "the most significant byte first". (According to learn.microsoft.com/de-de/dotnet/api/…) - otherwise, that would be a good fit.Vinegary

© 2022 - 2024 — McMap. All rights reserved.