我正在尝试将4个字节转换为32位无符号整数。
我想可能是这样的:
UInt32 combined = (UInt32)((map[i] << 32) | (map[i+1] << 24) | (map[i+2] << 16) | (map[i+3] << 8));
但这似乎不起作用。我错过了什么?
答案 0 :(得分:10)
你的班次全都是8。按24,16,8和0换班。
答案 1 :(得分:7)
使用BitConverter类。
具体而言,this overload.
答案 2 :(得分:4)
您可以随时执行以下操作:
public static unsafe int ToInt32(byte[] value, int startIndex)
{
fixed (byte* numRef = &(value[startIndex]))
{
if ((startIndex % 4) == 0)
{
return *(((int*)numRef));
}
if (IsLittleEndian)
{
return (((numRef[0] | (numRef[1] << 8)) | (numRef[2] << 0x10)) | (numRef[3] << 0x18));
}
return ((((numRef[0] << 0x18) | (numRef[1] << 0x10)) | (numRef[2] << 8)) | numRef[3]);
}
}
但这会重新发挥作用,因为这实际上是BitConverter.ToInt32()
的实施方式。