首先需要用到QString的静态成员函数来获取字符数组:
QByteArray QString::toLocal8Bit () ;//获取字节数组对象
char * QByteArray::data (); //通过字节数组对象的成员data函数,获取char数组
QTextCodec编码类介绍
互转主要用到这个类,通过该类可以获取编码对象,其中常见支持:
- UTF-8
- UTF-16 //默认大端
- UTF-16BE //大端,大数据开头, 比如字符a=00 61
- UTF-16LE //小端,小数据开头, 比如字符a=61 00
- UTF-32
- UTF-32BE
- UTF-32LE
- GB2312
- GBK等
比如获取utf-8编码对象:
QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //获取UTF-8编码对象
示例-utf8转为GBK
QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK")); //设置本地编码对象QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK")); //设置QString编码对象//utf8向gdk转换的过程是utf8->unicode, unicode->gdk//在PC,Unicode一般代表utf-16,而utf-8是单独列出来的//啊的gbk编码: 0xB0A1 啊的utf8编码:0xE5958A//哈的gbk编码: 0xB9FE 哈的utf8编码:0xE59388char encode[6]={0xe5,0x95,0x8A,0xE5,0x93,0x88}; //啊哈 utf-8编码QTextCodec *utf8 = QTextCodec::codecForName("UTF-8"); //获取UTF-8编码对象QString unicode = utf8->toUnicode(encode,6); //通过UTF-8编码对象将啊哈转为utf-16QTextCodec *gbk = QTextCodec::codecForName("GBK"); //获取GBK编码对象QByteArray arr=gbk->fromUnicode(unicode); //从Unicode编码转为自身编码类型(GBK)qDebug()<<QString::fromLocal8Bit(arr); //打印GBK码qDebug()<<arr.size();for(int i=0; i <arr.size();i++){qDebug("%x",(unsigned char)arr[i]);}
打印:
示例-GBK转为UTF8
QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK")); //设置本地编码对象QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK")); //设置QString编码对象//啊的gbk编码: 0xB0A1 啊的utf8编码:0xE5958A//哈的gbk编码: 0xB9FE 哈的utf8编码:0xE59388QString str="啊哈"; //对应编码为: 0xB0A1 0xB9FEQTextCodec *gbk = QTextCodec::codecForName("gbk");QString unicode=gbk->toUnicode(str.toLocal8Bit()); //通过gbk编码对象将啊哈转为utf-16QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");QByteArray arr=utf8->fromUnicode(unicode); //从Unicode编码转为自身编码类型(utf-8)qDebug()<<arr.size();for(int i=0; i <arr.size();i++){qDebug("%x",(unsigned char)arr[i]);}
打印
???????