Wes*_*eyE 13 c# integer endianness
我试图在C#中将一个4字节数组转换为ulong.我目前正在使用此代码:
atomSize = BitConverter.ToUInt32(buffer, 0);
Run Code Online (Sandbox Code Playgroud)
字节[4]包含:
0 0 0 32
但是,字节是Big-Endian.有没有一种简单的方法可以将这个Big-Endian ulong转换为Little-Endian ulong?
Mar*_*ers 19
我相信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
}
Run Code Online (Sandbox Code Playgroud)
用法:
atomSize = BitConverter.ToUInt32(buffer, 0);
atomSize = swapEndianness(atomSize);
Run Code Online (Sandbox Code Playgroud)
System.Net.IPAddress.NetworkToHostOrder(atomSize); 会翻转你的字节.
在 .net core (>= 2.1) 中,您可以改用它:
BinaryPrimitives.ReadUInt32BigEndian(buffer);
Run Code Online (Sandbox Code Playgroud)
这样,您就可以确定正在读取的字节序。
它在那里实施,以防您想知道它是如何工作的