分享一点代码(Qt 中GBK和UTF8的转换)

           日前发现,直接将GBK编码QString通过toUtf8转码后发现时乱码,查找资料后发现直接转换时有问题的,写了几个函数已供使用:


#include <QTextCodec>

inline QString GBK2UTF8(const QString &inStr)
{
	QTextCodec *gbk = QTextCodec::codecForName("GB18030");
	QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");

	QString g2u = gbk->toUnicode(gbk->fromUnicode(inStr));			  // gbk  convert utf8
	return g2u;
}

inline QString UTF82GBK(const QString &inStr)
{
	QTextCodec *gbk = QTextCodec::codecForName("GB18030");
	QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");

	QString utf2gbk = gbk->toUnicode(inStr.toLocal8Bit());
	return utf2gbk;
}

inline std::string gbk2utf8(const QString &inStr)
{
	return GBK2UTF8(inStr).toStdString();
}

inline QString utf82gbk(const std::string &inStr)
{
	QString str = QString::fromStdString(inStr);
	
	return UTF82GBK(str);
}

希望对大家有用:
Email: sunfrank#gmail.com


你可能感兴趣的:(String,qt,email)