简体   繁体   中英

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

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?

你的班次全都是8,按24,16,8和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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM