将int32存储在字节数组中

Blu*_*ron 0 c#

如何将int32存储在字节数组中的特定位置?

据我所知,我需要使用BitConverter.GetBytes(value); 得到字节[4].

然后我有一个byte [whatever_size]和offset.

public void SetInt32(byte[] message, int offset, Int32 value)
{
var value_bytes = BitConverter.GetBytes(value);
message[offset] = value_bytes;
}
Run Code Online (Sandbox Code Playgroud)

sam*_*moz 7

您可以使用按位算法直接获取字节:

byte temp[4];
temp[3] = value & 0xFF;
temp[2] = (value >> 8) & 0xFF;
temp[1] = (value >> 16) & 0xFF;
temp[0] = (value >> 24) & 0xFF;
for(int i = 0; i < 4; i++)
    message[offset+i] = temp[i];
Run Code Online (Sandbox Code Playgroud)