QT QBytearray和16进制字符串、QString互转、
2023-02-23 本文已影响0人
hao_developer
1. QString 转换为 Hex ByteArray
void SimSerialPort::convertStringToHex(const QString &str, QByteArray &byteData)
{
int hexdata,lowhexdata;
int hexdatalen = 0;
int len = str.length();
byteData.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 = convertCharToHex(hstr);
lowhexdata = convertCharToHex(lstr);
if((hexdata == 16) || (lowhexdata == 16))
break;
else
hexdata = hexdata*16+lowhexdata;
i++;
byteData[hexdatalen] = (char)hexdata;
hexdatalen++;
}
byteData.resize(hexdatalen);
}
//-----------
char SimSerialPort::convertCharToHex(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);
}
2. QByteArray转QString字符串
QByteArray bytes("hello world");
QString string = bytes; // QByteArray转QString方法1
QByteArray bytes("hello world");
QString string;
string.prepend(bytes);// QByteArray转QString方法2
3. QString字符串转QByteArray方法
//Qt5.3.2
QString str("hello");
QByteArray bytes = str.toUtf8(); // QString转QByteArray方法1
QString str("hello");
QByteArray bytes = str.toLatin1(); // QString转QByteArray方法2
4. 16进制字符串QString转换QByteArray
/*
* @breif 将16进制字符串转换为对应的字节序列
*/
QByteArray MainWindow::HexStringToByteArray(QString HexString)
{
bool ok;
QByteArray ret;
HexString = HexString.trimmed();
HexString = HexString.simplified();
QStringList sl = HexString.split(" ");
foreach (QString s, sl) {
if(!s.isEmpty())
{
char c = s.toInt(&ok,16)&0xFF;
if(ok){
ret.append(c);
}else{
qDebug()<<"非法的16进制字符:"<<s;
QMessageBox::warning(0,tr("错误:"),QString("非法的16进制字符: \"%1\"").arg(s));
}
}
}
qDebug()<<ret;
return ret;
}
5. QByteArray 转换为 16进制字符串QString
QString MainWindow::ByteArrayToHexString(QByteArray data){
QString ret(data.toHex().toUpper());
int len = ret.length()/2;
qDebug()<<len;
for(int i=1;i<len;i++)
{
qDebug()<<i;
ret.insert(2*i+i-1," ");
}
return ret;
}
6. QByteArray 转为unsigned char *
QByteArray byteArray;
unsigned char * p = (unsigned char *)byteArray.data();
附注:
16进制字符转QByteArray
QByteArray array;
array.resize(2);
// array[0]=0X00;
// array[1]=0X04;
bool ok;
char byte1=QString("00").toInt(&ok,16);
char byte2=QString("04").toInt(&ok,16);
array[0]=byte1;
array[1]=byte2;
QByteArray 存储字符
QByteArray bytes;
bytes.resize(5);
bytes[0] = '1';
bytes[1] = '2';
bytes[2] = '3';
bytes[3] = '\0';
bytes[4] = 'a';
cout << bytes << endl;
char 转16进制QString
char temp;
QString str = QString::number((unsigned char)temp, 16).toUpper().rightJustified(2, QChar('0'));