可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm trying to convert 4 bytes into a 32 bit unsigned integer.
I thought maybe something like:
UInt32 combined = (UInt32)((map[i] << 32) | (map[i+1] << 24) | (map[i+2] << 16) | (map[i+3] << 8));
But this doesn't seem to be working. What am I missing?
回答1:
Your shifts are all off by 8. Shift by 24, 16, 8, and 0.
回答2:
Use the BitConverter class.
Specifically, this overload.
回答3:
BitConverter.ToInt32()
You can always do something like this:
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]); } }
But this would be reinventing the wheel, as this is actually how BitConverter.ToInt32()
is implemented.