程序中在于外设打交到是常常会用到读硬件显示到控件,或是读控件写到硬件的情况,操作的最多的是字节流,所以肯定会用到QString 和QByteArray,下面测试一些常用的转换;
#include <QApplication> #include <QDebug> int main(int argv, char *argc[]) { QApplication app(argv, argc); //将16进制串转化成16进制数值组 //QStirng hex -> QByteArray hex QString str1("12345f"); QByteArray data1 = str1.toLocal8Bit(); QByteArray data2 = QByteArray::fromHex(data1); //将10进制串转化成16进制数值组 //QStirng int -> QByteArray hex bool ok; QByteArray data3, data4; QString str2 = "65534"; uint value = str2.toUInt(&ok, 10); str2 = str2.setNum(value, 16); data3 = str2.toLocal8Bit(); data4 = QByteArray::fromHex(data3); //将十六进制数组转换成十六进制串(Hex)串 //QByteArray hex -> QStirng hex QString str3; str3 = data2.toHex().toUpper(); //将十六进制数组转换成十进制串int串 //QByteArray hex -> QStirng int QString str4; value = (0xff00 & (data4.at(0) << 8)) | (0xff & data4.at(1)); str4.setNum(value); return app.exec(); }
运行结果