How can I combine 4 bytes into a 32 bit unsigned integer?

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!