[英]Integer to Byte Array In C#
以下代碼將一個int
轉換為一個byte
數組,表示該值的每個字符:
int value = 151219;
string stringValue = value.ToString(CultureInfo.InvariantCulture);
byte[] bytes = stringValue.Select(c => (byte) c).ToArray();
要將其插入到原始數組中,應執行以下操作:
private byte[] InsertInto(byte[] original, byte[] toInsert, int positionToInsert)
{
byte[] newArray = new byte[original.Length + toInsert.Length];
Array.Copy(original, newArray, positionToInsert);
Array.Copy(toInsert, 0, newArray, positionToInsert, toInsert.Length);
Array.Copy(original, positionToStart, newArray, positionToInsert + toInsert.Length, original.Length - positionToInsert);
return newArray;
}
您沒有整數數據類型,您有一個包含整數的字符串。 那是完全不同的。
您可以使用ASCIIEncoding.GetBytes
byte[] bytes = (new System.Text.ASCIIEncoding()).GetBytes("151219");
您可以像這樣連接兩個字節數組(給定兩個字節數組a
和b
):
byte[] result = new byte[ a.Length + b.Length ];
Array.Copy( a, 0, result, 0, a.Length );
Array.Copy( b, 0, result, a.Length, b.Length );
通過使用
System.Array.Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length)
您可以創建一個AppendInto方法,該方法將追加數組,並使用Encoding.ASCII.GetBytes
將字符串轉換為字節數組。
private byte[] AppendInto(byte[] original, byte[] toInsert, int appendIn)
{
var bytes = original.ToList();
bytes.InsertRange(appendIn, toInsert);
return bytes.ToArray();
}
然后只需使用功能
var toInsert = Encoding.ASCII.GetBytes("151219");
var original = new byte[11] { 0x01, 0x52, 0x35, 0x02, 0x50, 0x31, 0x28, 0x3B, 0x29, 0x03, 0x06 };
AppendInto(original, toInsert, 7);
結果
byte [17] {“ 0x01”,“ 0x52”,“ 0x35”,“ 0x02”,“ 0x50”,“ 0x31”,“ 0x28”,“ 0x31”,“ 0x35”,“ 0x31”,“ 0x32”,“ 0x31“,” 0x39“,” 0x3B“,” 0x29“,” 0x03“,” 0x06“}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.