【问题标题】:Efficient way to read big endian data in C#在 C# 中读取大端数据的有效方法
【发布时间】:2013-01-18 14:43:22
【问题描述】:

我使用以下代码使用BinaryReader 读取BigEndian 信息,但我不确定这是否是有效的方法。有没有更好的解决办法?

这是我的代码:

// some code to initialize the stream value
// set the length value to the Int32 size
BinaryReader reader =new BinaryReader(stream);
byte[] bytes = reader.ReadBytes(length);
Array.Reverse(bytes);
int result = System.BitConverter.ToInt32(temp, 0);

【问题讨论】:

    标签: c# endianness binaryreader


    【解决方案1】:

    BitConverter.ToInt32 首先不是很快。我会简单地使用

    public static int ToInt32BigEndian(byte[] buf, int i)
    {
      return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3];
    }
    

    您也可以考虑一次读取超过 4 个字节。

    【讨论】:

    • 谢谢 这很有趣,但为了确保我的想法正确,你能解释一下我们如何读取超过 4 个字节吗?
    • 只要调用更大长度的ReadBytes,然后用不同的is读取数组中不同位置的整数即可。但这是你应该只在基准测试之后进行的优化。
    • 是的,我在一些项目中使用了类似的东西(尽管不是在 C# 中)。但我原以为 BinaryReader/Writer 内置了字节序控制,这将使它更简单。
    【解决方案2】:

    截至 2019 年(实际上是从 .net core 2.1 开始),现在有

    byte[] buffer = ...;
    
    BinaryPrimitives.ReadInt32BigEndian(buffer.AsSpan());
    

    Documentation

    Implementation

    【讨论】:

      【解决方案3】:

      你可以使用IPAddress.NetworkToHostOrder,但我不知道它是否真的更有效。您必须对其进行概要分析。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多