将大端字节转换为整数?
Converting big endian bytes into integer?
我有这个 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。深入了解为什么会发生这种情况,否则将不胜感激。
忽略任何其他问题。有很多方法可以做到这一点,基本上你问的是如何获取一个字节数组来表示一个 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
通过这些方法确定你的系统的字节顺序,并反转大端架构的逻辑
我有这个 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。深入了解为什么会发生这种情况,否则将不胜感激。
忽略任何其他问题。有很多方法可以做到这一点,基本上你问的是如何获取一个字节数组来表示一个 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
通过这些方法确定你的系统的字节顺序,并反转大端架构的逻辑