C# Big-endian ulong from 4 bytes

2019-02-08 16:33发布

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?

6条回答
地球回转人心会变
2楼-- · 2019-02-08 16:37

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);
查看更多
我只想做你的唯一
3楼-- · 2019-02-08 16:41

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

查看更多
迷人小祖宗
4楼-- · 2019-02-08 16:42

I recommend using Mono's DataConvert which is like BitConverter on steroids. It allows you to read in big-endian byte arrays directly and improves massively on BitConverter.

A direct link to the source is here.

查看更多
Juvenile、少年°
5楼-- · 2019-02-08 16:48

This may be old but I'm surprised no one came up with this simplest answer yet, only requires one line...

// buffer is 00 00 00 32
Array.Reverse(buffer);
// buffer is 32 00 00 00
atomSize = BitConverter.ToUInt32(buffer, 0);

I'm using it to compare checksums generated in C# (little-endian) with checksums generated in Java (big-endian).

查看更多
Viruses.
6楼-- · 2019-02-08 16:50
BitConverter.ToUInt32(buffer.Reverse().ToArray(), 0)

No?

查看更多
Evening l夕情丶
7楼-- · 2019-02-08 16:58
firstSingle = BitConverter.ToSingle(buffer,0);
secondSingle = BitConverter.ToSingle(buffer,2); 

var result = BitConverter.ToUInt32(BitConverter.GetBytes(secondSingle).Concat(BitConverter.GetBytes(firstSingle).ToArray());
查看更多
登录 后发表回答