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

问题描述 投票:13回答:7

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

atomSize = BitConverter.ToUInt32(buffer, 0);

字节[4]包含:

0 0 0 32

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

c# integer endianness
7个回答
19
投票

我相信Jon Skeet的MiscUtil库(nuget link)中的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);

7
投票

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


5
投票

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

与源头的直接链接是here


4
投票
BitConverter.ToUInt32(buffer.Reverse().ToArray(), 0)

没有?


2
投票

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

// 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)。


1
投票

在.net core(> = 2.1)中,您可以利用它来代替:

BinaryPrimitives.ReadUInt32BigEndian(buffer);

这样,您就可以确定您正在阅读的字节顺序。

https://apisof.net/catalog/System.Buffers.Binary.BinaryPrimitives.ReadUInt32BigEndian(ReadOnlySpan%3CByte%3E)

它是在那里实现的,如果你想知道它是如何工作的:https://github.com/dotnet/coreclr/blob/de68c9ddd18f863fd67098ab28d19206c9c66627/src/System.Private.CoreLib/shared/System/Buffers/Binary/ReaderBigEndian.cs#L75


0
投票
firstSingle = BitConverter.ToSingle(buffer,0);
secondSingle = BitConverter.ToSingle(buffer,2); 

var result = BitConverter.ToUInt32(BitConverter.GetBytes(secondSingle).Concat(BitConverter.GetBytes(firstSingle).ToArray());
© www.soinside.com 2019 - 2024. All rights reserved.