问题描述
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。了解为什么会发生这种情况,否则将不胜感激。
解决方法
忽略任何其他问题。有很多方法可以做到这一点,实际上,您要问的是如何获取一个表示 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
注意,您还应该使用BitConverter.IsLittleEndian == false
通过这些方法确定系统的字节序,并反转大字节序体系结构上的逻辑