C# Big-endian ulong from 4 bytes

Viewed 18507

Im trying to cast a 4 byte array to an ulong in C#. I'm currently using this code:

atomSize = BitConverter.ToUInt32(buffer, 0);

The byte[4] contains this:

0 0 0 32

However, the bytes are Big-Endian. Is there a simple way to convert this Big-Endian ulong to a Little-Endian ulong?

7 Answers

In .net core (>= 2.1), you can use this instead:

BinaryPrimitives.ReadUInt32BigEndian(buffer);

That way, you're sure of the endianness you're reading from.

Documentation

It's implemented there in case you're wondering how it works

Edit: as mentionned by @smkanadl in the comments, it seems that you can use this API as well in .net framework by installing the System.Memory package.

Related