在C#中将Big endian转换为Little endian



让我首先说,我已经看了一些关于Stackoverflow的帖子。我的问题是,我是一个初级程序员,很难将这些解决方案配置到我的项目中。

我目前正在努力将一个"big-endian"转换为一个"little-endian"。

目前有一个浮动:

(4.61854E-41(

但我想以某种方式将其转换为这样:

(-1.0(

如有任何帮助,我们将不胜感激。

看看BitConverter

首先检查系统是否为小端序,然后根据情况反转字节。

float num = 1.2f;
if (!BitConverter.IsLittleEndian)
{
byte[] bytes = BitConverter.GetBytes(num);
Array.Reverse(bytes, 0, bytes.Length);
num = BitConverter.ToSingle(bytes, 0);
}
Console.WriteLine(num);

2022年,正确的做法是使用BinaryPrimitives

float num = 1.2f;
if (!BitConverter.IsLittleEndian)
{
int bits = BitConverter.SingleToInt32Bits(num);
int revBits = BinaryPrimitives.ReverseEndianness(bits);
num = BitConverter.Int32BitsToSingle(revBits);
}
Console.WriteLine(num);

这在性能方面优化得更好,并且在现代x86处理器上使用bswap指令。这方面的ARM等价物是REV32

请参阅JIT CodeGen与@sLw的答案之间的差异。

BinaryPrimitives可从.NET Core 2.1和.NET Standard 2.1中获得。作为.NET Framework用户,遗留方式仍然是最好的方式(参考:.NET API目录(。

最新更新