如何将4个字节组合成32位无符号整数?

我正在尝试将4个字节转换为32位无符号整数。

我想也许是这样的:

UInt32 combined = (UInt32)((map[i] << 32) | (map[i+1] << 24) | (map[i+2] << 16) | (map[i+3] << 8)); 

但这似乎并没有奏效。 我错过了什么?

你的class次全都偏离8.转移24,16,8和0。

使用BitConverter类。

具体来说, 这个超载。

BitConverter.ToInt32()

你总是可以这样做:

 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()的实现方式。