【问题标题】:Converting big endian bytes into integer?将大端字节转换为整数?
【发布时间】:2020-10-04 18:02:47
【问题描述】:

我有这个 python 代码:

f = open('file.bin', 'rb')
b = f.read(2)
bytes = b[0x0:0x2] //this is b'\x10\x24', for example
f.close()
a = int.from_bytes(bytes, 'big') //returns 4132

我似乎无法弄清楚如何在 C# 中实现同样的功能。

确实找到了这个方法:

public static int IntFromBigEndianBytes(byte[] data, int startIndex = 0)
    {
      return (data[startIndex] << 24) | (data[startIndex + 1] << 16) | (data[startIndex + 2] << 8) | data[startIndex + 3];
    }

尝试该方法总是会导致 IndexOutOfRangeException,因为我的输入字节小于 4。了解为什么会发生这种情况,否则任何信息将不胜感激。

【问题讨论】:

    标签: python c# endianness


    【解决方案1】:

    忽略任何其他问题。有很多方法可以做到这一点,基本上你要问的是如何获取一个表示 16 位 值的字节数组(short,Int16)并将其分配给int

    给定

    public static int IntFromBigEndianBytes(byte[] data) 
        => (data[0] << 8) | data[1];
    
    public static int IntFromBigEndianBytes2(byte[] data) 
        => BitConverter.ToInt16(data.Reverse().ToArray());
    

    用法

    var someArray = new byte[]{0x10, 0x24};
    
    Console.WriteLine(IntFromBigEndianBytes(someArray));
    Console.WriteLine(IntFromBigEndianBytes2(someArray));
    

    输出

    4132
    4132
    

    Full Demo Here

    注意您还应该使用BitConverter.IsLittleEndian == false 通过这些方法确定系统的字节序,并在大字节序架构上反转逻辑

    【讨论】:

    • 这太好了,谢谢。但是,Convert.ToInt32(array.Hex()), 16); 也成功了,.Hex() 将字节转换为十六进制字符串。
    猜你喜欢
    • 1970-01-01
    • 2016-02-06
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多