C#Big-endian ulong来自4个字节

我试图在C#中将4字节数组转换为ulong。 我目前正在使用此代码:

atomSize = BitConverter.ToUInt32(buffer, 0); 

字节[4]包含:

0 0 0 32

但是,字节是Big-Endian。 有没有一种简单的方法可以将这个Big-Endian ulong转换为Little-Endian ulong?

我相信Jon Skeet的MiscUtil库( nuget链接 )中的EndianBitConverter可以做你想要的。

您还可以使用位移操作交换位:

 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 } 

用法:

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

System.Net.IPAddress.NetworkToHostOrder(atomSize); 会翻转你的字节。

我建议使用Mono的DataConvert ,就像类固醇上的BitConverter一样。 它允许您直接读取大端字节数组并在BitConverter大量改进。

这里有直接链接到源。

 BitConverter.ToUInt32(buffer.Reverse().ToArray(), 0) 

没有?

这可能是旧的,但我很惊讶没有人想出这个最简单的答案,只需要一行……

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

我用它来比较在C#(little-endian)中生成的校验和与用Java生成的校验和(big-endian)。

 firstSingle = BitConverter.ToSingle(buffer,0); secondSingle = BitConverter.ToSingle(buffer,2); var result = BitConverter.ToUInt32(BitConverter.GetBytes(secondSingle).Concat(BitConverter.GetBytes(firstSingle).ToArray());