如何将4个字节组合成32位无符号整数?

Poc*_*cki 8 c# bit-manipulation

我正在尝试将4个字节转换为32位无符号整数.

我想也许是这样的:

UInt32 combined = (UInt32)((map[i] << 32) | (map[i+1] << 24) | (map[i+2] << 16) | (map[i+3] << 8));
Run Code Online (Sandbox Code Playgroud)

但这似乎并没有起作用.我错过了什么?

Ign*_*ams 10

你的班次全都是8,按24,16,8和0换班.

  • 字节的值占用第1位到第8位.您希望将其移位24位,使其占用位24到32位.如果移位32位,则会将其移至遗忘状态. (2认同)

Rob*_*vey 7

使用BitConverter类.

具体来说,这个超载.

  • @Pocki:是的,*转换是特定于字节序的.*类有一个特定于系统的标志来调整转换.相关代码如下所示:`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]);` (2认同)

Ale*_*Aza 5

BitConverter.ToInt32()

你总是可以做这样的事情:

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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

但这将是重新发明轮子,因为这实际上是如何BitConverter.ToInt32()实现的。