1 #include <QCoreApplication> 2 #include <QDebug> 3 #include <QDataStream> 4 5 QByteArray HexStringToByteArray(QString HexString) 6 { 7 bool ok; 8 QByteArray ret; 9 HexString = HexString.trimmed(); 10 HexString = HexString.simplified(); 11 QStringList sl = HexString.split(" "); 12 13 foreach (QString s, sl) { 14 if(!s.isEmpty()) { 15 char c = s.toInt(&ok,16)&0xFF; 16 if(ok){ 17 ret.append(c); 18 }else{ 19 qDebug()<<"非法的16进制字符:"<<s; 20 } 21 } 22 } 23 return ret; 24 } 25 26 QString ByteArrayToHexString(QByteArray &ba) 27 { 28 QDataStream out(&ba,QIODevice::ReadWrite); //将str的数据 读到out里面去 29 QString buf; 30 while(!out.atEnd()) 31 { 32 qint8 outChar = 0; 33 out >> outChar; //每次一个字节的填充到 outchar 34 QString str = QString("%1").arg(outChar&0xFF,2,16,QLatin1Char(‘0‘)).toUpper() + QString(" "); //2 字符宽度 35 buf += str; 36 } 37 return buf; 38 } 39 40 int main(int argc, char *argv[]) 41 { 42 QCoreApplication a(argc, argv); 43 char cmd[7] = {0x40, 0x00, 0x00, 0x01, 0x00, 0x41, 0x0A}; 44 char* cmdString = "40 00 00 01 00 41 0a"; 45 QByteArray cmdBA = HexStringToByteArray(cmdString); 46 qDebug()<<ByteArrayToHexString(cmdBA); 47 48 return a.exec(); 49 }
原文地址:https://www.cnblogs.com/ch122633/p/8393406.html
时间: 2024-11-15 01:02:22