如何追加字符串和字节数组?
String array="$MT!BOOTLOADER";
Byte[] hexdecimal={0x01,0x05,0x0036};
答案 0 :(得分:2)
你可能想要做一些低级别的事情,所以最后你不需要string
而是byte[]
,所以:
string array="$MT!BOOTLOADER";
byte[] hexdecimal={0x01,0x05,0x36};
byte[] bytesOrig = Encoding.ASCII.GetBytes(array);
byte[] bytesFinal = bytesOrig;
Array.Resize(ref bytesFinal, bytesFinal.Length + hexdecimal.Length);
Array.Copy(hexdecimal, 0, bytesFinal, bytesOrig.Length, hexdecimal.Length);
// bytesFinal contains all the bytes
我正在使用Encoding.ASCII
,因为您的签名是ASCII(通常签名是 ASCII)
等效代码,但差别不大(我们通过对Encoding.ASCII
方法进行两次调用来预先分配具有正确大小的数组)
string array="$MT!BOOTLOADER";
byte[] hexdecimal={0x01,0x05,0x36};
int count = Encoding.ASCII.GetByteCount(array);
byte[] bytes = new byte[count + hexdecimal.Length];
Encoding.ASCII.GetBytes(array, 0, array.Length, bytes, 0);
Array.Copy(hexdecimal, 0, bytes, count, hexdecimal.Length);
// bytes contains all the bytes
答案 1 :(得分:0)
使用此功能转换string to byte
和byte to string
。
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}