16进制字符串转QByteArray,char转16进制字符串

直接上代码,看代码你们就懂了

1、16进制QString转QByteArray

 1 QString str = "01 a5 1e 02";
 2 QByteArray tmpBy;
 3 StringToHex(str, tmpBy);
 4 
 5 void MainWindow::StringToHex(QString str, QByteArray &senddata)
 6 {
 7     int hexdata,lowhexdata;
 8     int hexdatalen = 0;
 9     int len = str.length();
10     senddata.resize(len/2);
11     char lstr,hstr;
12     for(int i=0; i<len; )
13     {
14         //char lstr,
15         hstr=str[i].toLatin1();
16         if(hstr == ' ')
17         {
18             i++;
19             continue;
20         }
21         i++;
22         if(i >= len)
23             break;
24         lstr = str[i].toLatin1();
25         hexdata = ConvertHexChar(hstr);
26         lowhexdata = ConvertHexChar(lstr);
27         if((hexdata == 16) || (lowhexdata == 16))
28             break;
29         else
30             hexdata = hexdata*16+lowhexdata;
31         i++;
32         senddata[hexdatalen] = (char)hexdata;
33         hexdatalen++;
34     }
35     senddata.resize(hexdatalen);
36 }
37 
38 char MainWindow::ConvertHexChar(char ch)
39 {
40     if((ch >= '0') && (ch <= '9'))
41         return ch-0x30;
42     else if((ch >= 'A') && (ch <= 'F'))
43         return ch-'A'+10;
44     else if((ch >= 'a') && (ch <= 'f'))
45         return ch-'a'+10;
46     else return ch-ch;//不在0-f范围内的会发送成0
47 }

2、qint8(signed char)转16进制字符串

 1     QDataStream out(&requestData,QIODevice::ReadWrite);    //将字节数组读入
 2     QString strReceive;
 3     int index = 0;
 4     while(!out.atEnd())
 5     {
 6         qint8 outChar = 0;
 7         out>>outChar;   //每字节填充一次,直到结束
 8         //十六进制的转换
 9         QString str = QString("%1").arg(outChar & 0xFF,2,16,QLatin1Char('0'));
10         strReceive.append(str);
11     }

3、这块我主要是用在串口通信这里了,看自己实际情况吧

posted @ 2018-08-23 09:54  徐沛东  阅读(4267)  评论(0编辑  收藏  举报