一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

1、QString转换成十六进制

 1 void ConvertQStringToHex(const QString &str,const QByteArray& byte)
 2 {
 3     int hexData,lowhexData;
 4     int hexdataLen=0;
 5     int len = str.length();
 6     byte.resize(len/2);
 7     char lstr,hstr;
 8     for(int i=0;i<len;)
 9     {
10         hstr = str[i].toLatin1();
11         if(hstr ==' ')
12         {
13             i++;
14             continue;
15         }
16         i++;
17         if(i>=len)
18         {
19             break;
20         }
21         lstr = str[i].toLatin1();
22         hexData = ConvertCharToHex(hstr);
23         lowhexData = ConvertCharToHex(lstr);
24         if((hexData == 16)|| (lowhexData==16))
25         {
26             break;
27         }
28         else
29         {
30             hexData = hexData*16+lowhexData;
31         }
32         i++;
33         byte[hexdatalen] = (char)hexData;
34         hexdataLen++;
35     }
36     byte.resize(hexdataLen);
37 }

2、char转十六进制

 1 char ConvertCharToHex(char ch)
 2 {
 3     if((ch >= '0') && (ch <= '9'))
 4          return ch-0x30;
 5      else if((ch >= 'A') && (ch <= 'F'))
 6          return ch-'A'+10;
 7      else if((ch >= 'a') && (ch <= 'f'))
 8          return ch-'a'+10;
 9     else return (-1);
10 }

3、QByteArray转QString

1 QByteArray array("Hello World");
2 QString str = array;
3 4 str.prepend(array);

4、将16进制QString转换成QByteArray

 1 QByteArray HexStringToByteArray(QString HexString)
 2 {
 3     bool ok;
 4     QByteArray ret;
 5     HexString = HexString.trimmed();
 6     HexString = HexString.simplified();
 7     QStringList sl = HexString.split(" ");
 8 
 9     foreach (QString s, sl) {
10         if(!s.isEmpty())
11         {
12             char c = s.toInt(&ok,16)&0xFF;
13             if(ok)
14             {
15                 ret.append(c);
16             }
17             else
18             { }
19         }
20     }
21     return ret;
22 }

5、QByteArray转16进制QString

 1 QString MainWindow::ByteArrayToHexString(QByteArray data)
 2 {
 3     QString ret(data.toHex().toUpper());
 4     int len = ret.length()/2;
 5     qDebug()<<len;
 6     for(int i=1;i<len;i++)
 7     {
 8         ret.insert(2*i+i-1," ");
 9     }
10 
11     return ret;
12 }

 

posted on 2023-03-14 11:27  一杯清酒邀明月  阅读(957)  评论(0编辑  收藏  举报