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

I am trying to convert 4 bytes to an unsigned 32-bit 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 does not seem to work. What am I missing?

+6
source share
3 answers

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

+9
source

Use the BitConverter class.

In particular, this overload.

+7
source

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 will reinvent the wheel, since in reality it is like BitConverter.ToInt32() .

+3
source

Source: https://habr.com/ru/post/890889/


All Articles