[英]storing int32 in a byte array
如何將 int32 存儲在字節數組中的特定位置?
據我所知,我需要使用 BitConverter.GetBytes(value); 獲取字節[4]。
然后我有一個字節 [whatever_size] 和偏移量。
public void SetInt32(byte[] message, int offset, Int32 value)
{
var value_bytes = BitConverter.GetBytes(value);
message[offset] = value_bytes;
}
您可以使用按位算術直接獲取字節:
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];
您可以使用BitConverter
然后使用Buffer.BlockCopy
或Array.Copy
將“新”字節數組的內容復制到另一個數組中。
或者,您可以從MiscUtil 中獲取EndianBitConverter
代碼,它不僅允許您指定字節順序,還允許您避免創建冗余數組:
EndianBitConverter.Little.CopyBytes(value, message, offset);
采用
value_bytes.CopyTo(message, offset);
代替
message[offset] = value_bytes;
假設該message
是您的其他字節數組,而offset
是指定要復制的位置的 int。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.