/*
* author: hjjdebug
* date: 2017年 09月 01日 星期五 22:35:38 CST
* 说明:
* 有一个打印机,只支持gdk编码, 而我的程序是linux, utf8是本地编码.
我需要一个简单的utf8向gdk转换的程序. 网上大多不能直接使用,
下面附上自己整理和测试的代码. 花了我不少时间, QT 环境.
代码解读: utf8 与 gdk 不能直接进行转换,而需要借助于unicode来进行变换.
utf8向gdk转换的过程是utf8->unicode, unicode->gdk.
第一步变换需要utf8 QTextCodec,
第二步变换需要gdk QTextCodec,
同理, gbk 向utf8转换也是一样
请重点关注他们的char *p内容的变化.
至于包在QString里,还是包在QByteArray里,这不重要.
付测试代码!!
"您好" utf8编码: e6 82 a8 e5 a5 bd
"您好" gbk编码: c4 fa ba c3
*/
- #include <stdio.h>
- #include <string.h>
- #include <QString>
- #include <QTextCodec>
-
- void printContent(char *p)
- int main()
- {
- QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");
- QTextCodec::setCodecForLocale(utf8);
- QTextCodec::setCodecForCStrings(utf8);
- QTextCodec* gbk = QTextCodec::codecForName("gbk");
-
- unsigned int i;
- QString str1="您好";
- char *p=str1.toLocal8Bit().data(); //如此可以等到它的char*
- printContent(p);
-
- //utf8 -> gbk
- //1. utf8 -> unicode
- QString strUnicode= utf8->toUnicode(str1.toLocal8Bit().data());
- //2. unicode -> gbk, 得到QByteArray
- QByteArray gb_bytes= gbk->fromUnicode(strUnicode);
- p = gb_bytes.data(); //获取其char *
- printContent(p);
-
- //gbk -> utf8
- //1. gbk to unicode
- strUnicode=gbk->toUnicode(p);
- //2. unicode -> utf-8
- QByteArray utf8_bytes=utf8->fromUnicode(strUnicode);
- p = utf8_bytes.data(); //获取其char *
- printContent(p);
- }
-
- void printContent(char *p)
- {
- //打印其内容, char *
- for(i=0;i<strlen(p);i++)
- printf("%02x ",(unsigned char)p[i]);
- printf("\n");
- }
|