C# Big-endian ulong from 4 bytes

I believe that the EndianBitConverter in Jon Skeet's MiscUtil library (nuget link) can do what you want.

You could also swap the bits using bit shift operations:

uint swapEndianness(uint x)
{
    return ((x & 0x000000ff) << 24) +  // First byte
           ((x & 0x0000ff00) << 8) +   // Second byte
           ((x & 0x00ff0000) >> 8) +   // Third byte
           ((x & 0xff000000) >> 24);   // Fourth byte
}

Usage:

atomSize = BitConverter.ToUInt32(buffer, 0);
atomSize = swapEndianness(atomSize);

System.Net.IPAddress.NetworkToHostOrder(atomSize); will flip your bytes.


In .net core (>= 2.1), you can leverage 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