QString、QByteArray 的等效转换:
QByteArray = QString.toUtf8();// 转换为Unicode字符集编码,多字节编码,单个中文占3~4个字节
QByteArray = QString.toLocal8Bit();// 转换为GB2312/GBK字符集编码,单个中文占2个字节
QString = QByteArray;
QString、QByteArray asc2转换为16进制显示:
QByteArray可以直接转换为16进制显示:QByteArray.toHex()
QString不能直接转换为16进制显示,要先转换为QByteArray,再16进制显示:
QString.toUtf8().toHex()// 转换为Unicode字符集编码
QString.toLocal8Bit().toHex()// 转换为GB2312/GBK字符集编码
QString的16进制显示转换为 asc2显示:
QString txtBuf = "616263414243";// "abcABC"的16进制显示
QString/QByteArray str1 = QByteArray::fromHex(txtBuf.toUtf8());// 这种转换方式可忽略掉中间空格
QTextEdit显示GB2312中文:
GB2312/GBK/GB18030区别:https://www.zhihu.com/question/19677619
GB2312/GBK采用双字节编码。GB18030采用多字节编码,每个字可以由 1 个、2 个或 4 个字节组成。
GB2312的中文是2字节,unicode/UTF8/16的中文是3~4个字节。而Qt控件的QString都是以unicode编码的,所以gb2312编码的中文不能直接放到QString里,会显示乱码,需要做下转换:
// 将GB2312编码转换成unicode,并用QTextEdit显示
QString str = "中文";
QString sendData = QTextCodec::codecForName("GB2312")->toUnicode(str.toLocal8Bit());// 使用toLocal8Bit()转换为GB2312编码,再用QTextCodec将GB2312转换为Unicode
ui->txtSend->setText(sendData);// 中文显示正常
综合例程:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QTextCodec>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QString str = "中文";
// QString 与 QByteArray 相互转换
QString sendData_1 = str.toUtf8();// 中文正常显示。sendData_1/2/x 类型为 QByteArray 也是一样的效果
QString sendData_2 = str.toLocal8Bit();// 中文显示乱码
// 将原码转换为16进制。为了看清内存中存储的数据内容
QString sendData_3 = str.toUtf8().toHex().toUpper();// Unicode字符集中的"中文"编码,多字节编码,单个中文占3~4个字节
QString sendData_4 = str.toLocal8Bit().toHex().toUpper();// GB2312/GBK字符集中的"中文"编码,双字节编码,单个中文占2个字节
// 将QString由16进制,转换为原码,且这种方式可以忽略中间的空格
QString sendData_5 = QByteArray::fromHex(str.toUtf8().toHex());// 中文正常显示
QString sendData_6 = QByteArray::fromHex(str.toLocal8Bit().toHex());// 中文显示乱码
// 将GB2312编码转换成unicode
QString sendData_7 = QTextCodec::codecForName("GB2312")->toUnicode(str.toLocal8Bit());// 中文正常显示
QString sendData_8 = QTextCodec::codecForName("GB2312")->toUnicode(QByteArray::fromHex(str.toLocal8Bit().toHex()));// 中文正常显示
ui->txtSend_1->setText(sendData_1);
ui->txtSend_2->setText(sendData_2);
ui->txtSend_3->setText(sendData_3);
ui->txtSend_4->setText(sendData_4);
ui->txtSend_5->setText(sendData_5);
ui->txtSend_6->setText(sendData_6);
ui->txtSend_7->setText(sendData_7);
ui->txtSend_8->setText(sendData_8);
}
MainWindow::~MainWindow()
{
delete ui;
}
运行结果: