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

前端 未结 3 1376
逝去的感伤
逝去的感伤 2021-01-04 23:22

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         


        
3条回答
  •  逝去的感伤
    2021-01-05 00:06

    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.

提交回复
热议问题