簡體   English   中英

C#中的整數到字節數組

[英]Integer to Byte Array In C#

如何將int轉換為Byte Array,並將其他追加到byte Array。

例如

我想將其轉換為151219

new byte[6] { 0x31, 0x35, 0x31, 0x32, 0x31, 0x39 }`

並附加到:

new byte[17] { 0x01, 0x52, 0x35, 0x02, 0x50, 0x31, 0x28, --- append here ---, 0x3B, 0x29, 0x03, 0x06 }

http://www.nthelp.com/ascii.htm

以下代碼將一個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");

您可以像這樣連接兩個字節數組(給定兩個字節數組ab ):

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM