Skip to content

Instantly share code, notes, and snippets.

@lixingcong
Created June 27, 2018 04:01
Show Gist options
  • Save lixingcong/76973d95ba4cccdce5d5d1d12f812f63 to your computer and use it in GitHub Desktop.
Save lixingcong/76973d95ba4cccdce5d5d1d12f812f63 to your computer and use it in GitHub Desktop.
Qt4 Qt5的GBK解码
#include <QCoreApplication>
#include <QDebug>
#include "qt_gbk_stringdecoder.h"
#include "qt_gbk_strs.h"
int main(int argc, char *argv[])
{
//QCoreApplication a(argc, argv);
#if QT_VERSION < 0x050000
// Qt5已经默认为UTF-8编码。这里仅针对Qt4的设置编码
QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForTr(utf8);
QTextCodec::setCodecForLocale(utf8);
QTextCodec::setCodecForCStrings(utf8);
#endif
qDebug()<<"good good study, day day up";
QString s=stringDecoder::gbkCharToQString(demo_s);
qDebug()<<s;
qDebug()<<QByteArray(s.toLocal8Bit().data(), 10).toHex();
qDebug()<<QByteArray(demo_s, 10).toHex();
//return a.exec();
return 0;
}
#ifndef STRINGDECODER_H
#define STRINGDECODER_H
#include <QTextCodec>
namespace stringDecoder{
// https://blog.csdn.net/hejinjing_tom_com/article/details/77780565
inline QString gbkCharToQString(const char* str_in)
{
QTextCodec* gbk = QTextCodec::codecForName("GB18030");
if(!gbk)
return "Wrong QTextCodec";
// 注意Qt4下,需要先使用setCodecForLocale()和setCodecForCStrings()设定默认的QString编码
return gbk->toUnicode(str_in);
}
}
#endif // STRINGDECODER_H
#include "qt_gbk_strs.h"
// 这是一个GBK编码的文件
char demo_s[MAX_CHAR_LEN]="您好";
/*
"您好" utf8 编码: e6 82 a8 e5 a5 bd
"您好" gbk 编码: c4 fa ba c3
*/
#ifndef STRS_H
#define STRS_H
// 这是一个GBK编码的文件
#define MAX_CHAR_LEN 40
extern char demo_s[MAX_CHAR_LEN];
#endif // STRS_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment