void Widget::StringToHex(QString str, QByteArray &senddata) // 字符串转换为十六进制数据0-F
{
int hexdata, lowhexdata;
int hexdatalen = 0;
int len = str.length();
senddata.resize(len / 2);
char lstr, hstr;
for (int i = 0; i < len;)
{
// char lstr,
hstr = str[i].toLatin1();
if (hstr == ' ')
{
i++;
continue;
}
i++;
if (i >= len)
break;
lstr = str[i].toLatin1();
hexdata = ConvertHexChar(hstr);
lowhexdata = ConvertHexChar(lstr);
if ((hexdata == 16) || (lowhexdata == 16))
break;
else
hexdata = hexdata * 16 + lowhexdata;
i++;
senddata[hexdatalen] = (char)hexdata;
hexdatalen++;
}
senddata.resize(hexdatalen);
}
char Widget::ConvertHexChar(char ch)
{
if ((ch >= '0') && (ch <= '9'))
return ch - 0x30;
else if ((ch >= 'A') && (ch <= 'F'))
return ch - 'A' + 10;
else if ((ch >= 'a') && (ch <= 'f'))
return ch - 'a' + 10;
else
return ch - ch; // 不在0-f范围内的会发送成0
}
示例:
QString str_buf = "123456789";
QByteArray senddata;
StringToHex(str_buf ,senddata);
结果 senddata = {0x12,0x34,0x56,0x78,0x09}