[英]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.