需求
将字符串形式的多位字节信息转换为对应的字节数组,例如
输入:“1A2B3C4D“
输出:{ 0x1A, 0x2B, 0x3C, 0x4D }
代码
private byte[] StringToBytes(string s)
{
int sLen = s.Length;
int bytesLen = sLen / 2;
byte[] bytes = new byte[bytesLen];
int position = 0;
for(int i = 0; i < bytesLen; i++)
{
string abyte = s.Substring(position, 2);
bytes[i] = Convert.ToByte(abyte, 16);
position += 2;
}
return bytes;
}
使用中发现,如果字符串中含有空格,则转换过程会出错,而实际使用中,可能字节的形式会是”1A 2B 3C“或者"1A-2B-3C"
为了实现对空格和短横线的识别,对代码进行修改如下
private byte[] StringToBytes(string s)
{
string[] str = s.Split(' ');
int n = str.Length;
byte[] cmdBytes = null;
int p = 0;
for (int k = 0; k < n; k++)
{
int sLen = str[k].Length;
int bytesLen = sLen / 2;
int position = 0;
byte[] bytes = new byte[bytesLen];
for (int i = 0; i < bytesLen; i++)
{
string abyte = str[k].Substring(position, 2);
bytes[i] = Convert.ToByte(abyte, 16);
position += 2;
}
if (position >= 2)
{
byte[] cmdBytes2 = new byte[p + bytesLen];
if (cmdBytes != null)
{
Array.Copy(cmdBytes, 0, cmdBytes2, 0, p);
}
Array.Copy(bytes, 0, cmdBytes2, p, bytesLen);
cmdBytes = cmdBytes2;
p += bytesLen;
}
}
return cmdBytes;
}
代码大意为,首先对字符串按空格进行切分,然后按短横线进行切分,再将切分后的字符串分别转换、拼接
由此,实现了字符串转换为字节数组