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

Converting Big endian to Little endian in C#

首先让我说,我已经查看了 Whosebug 上的一些 post。我的问题是我是一名初级程序员,很难将解决方案配置到我的项目中。

我目前正在努力将一个 '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);

这是更好地优化 performance-wise 并在现代 x86 处理器上使用 bswap 指令。 ARM 的等价物是 REV32.

JIT-CodeGen diff between this and the

BinaryPrimitives 可从 .NET Core 2.1 和 .NET Standard 2.1 获得。 作为 .NET Framework 用户,传统方式仍然是最好的方式(参考:.NET API Catalog)。