Qt|QString与QByteArray互转、字符串转十六进制

1、QByteArray转QString,主要用buf.toHex()即可:

static QString ByteArrayToHexStr(QByteArray buf) { QString retStr; retStr.append(buf.toHex()); return retStr; }

2、QString转QByteArray
//第一种:data.toLatin1() static QByteArray TwoHexStrToByteArray(QString data) { QByteArray buf; buf = data.toLatin1(); return buf; }

//第二种:data.toUtf8()也可以 static QByteArray TwoHexStrToByteArray(QString data) { QByteArray bytes = data.toUtf8(); // QString转QByteArray方法1 return bytes; }

//第三种:直接截取在转也可以 static QByteArray TwoHexStrToByteArray(QString data) { QByteArray buf; for(int i = 0; i < data.length(); i += 2) { bool ok; char chr = (data.mid(i, 2).toInt(&ok, 16)) & 0xFF; buf.append(chr); } return buf; }

【Qt|QString与QByteArray互转、字符串转十六进制】3、十六进制字符串转十六进制编码
char 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 (-1); } void StringToHex(QString str, QByteArray &senddata) { int hexdata,lowhexdata; int hexdatalen = 0; int len = str.length(); senddata.resize(len/2); char lstr,hstr; for(int i=0; i= len) break; lstr = str[i].toAscii(); hexdata = https://www.it610.com/article/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); }


    推荐阅读