前言

在使用QT进行串口通信时候总会涉及到QByteArray和QString互相转换还有十六进制的问题,这里写一下大概转换的方法

转换

QString 转 QByteArray

以下这三种都可以,区别主要是表现的字符集范围,详细看官方注释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
QString str("HelloWorld");  
QByteArray bytes = str.toUtf8();
/**Returns a UTF-8 representation of the string as a QByteArray.
UTF-8 is a Unicode codec and can represent all characters
in a Unicode string like QString. **/
QByteArray bytes = str.toLocal8Bit(); //
/**Returns the local 8-bit representation of the string as a QByteArray.
The returned byte array is undefined if the string contains
characters not supported by the local 8-bit encoding.**/
QByteArray bytes = str.toLatin1();
/**Returns a Latin-1 representation of the string as a QByteArray.
The returned byte array is undefined if the string contains
non-Latin1 characters. Those characters may be suppressed
or replaced with a question mark.**/

QByteArray 转 QString

1
2
3
4
5
6
7
8
9
QByteArray bytes("HelloWorld");

QString str = bytes;
//注意如果bytes的二进制字节数组中存在'\0'这种在QString中被认为是结束符的符号,
//会使QString只获取到'\0'前的内容

QString strbytes = QString::fromLatin1(bytes, bytes.size());
//使用这种方式就不会存在上述问题
//同样也有 QString::fromUtf8() QString::toLocal8Bit()

十六进制明文QString 转 QByteArray

1
2
3
QString text("48656C6C6F576F7264");//"HelloWorld"
QByteArray data = QByteArray::fromHex(text.toUtf8());
qDebug() << data; //输出 HelloWorld