C#中的整数到字节数组

Integer to Byte Array In C#

如何将 int 转换为字节数组,并将 other 附加到字节数组。

例如

我想将它 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 }

以下代码会将 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" }