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

北慕城南 提交于 2019-11-30 20:06:00

Your shifts are all off by 8. Shift by 24, 16, 8, and 0.

Use the BitConverter class.

Specifically, this overload.

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.

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