当前位置:网站首页>Qt Utf8 与 Unicode 编码的互相转换, Unicode编码输出为格式为 &#xXXXX

Qt Utf8 与 Unicode 编码的互相转换, Unicode编码输出为格式为 &#xXXXX

2022-06-25 22:00:00 北极熊的奋斗史

先上结果:

      utf-8文字:  这是测试文字123456abcdefg 

      Unicode码: 杩欐槸娴嬭瘯鏂囧瓧123456abcdefg

 

上代码:

1. utf8转Unicode码

QString utf8ToUnicode(const QString strUtf8)
{
    QString strOut;
    QString unidata = strUtf8;
    for (int i = 0; i < unidata.length(); ++i)
    {
        ushort num = unidata[i].unicode();
        if (num < 255)
            strOut += unidata[i];
        else
            strOut += QString("&#x%1;").arg(QString::number(num, 16));
    }
    
    return strOut;
}

 2. Unicode转utf8

QString unicodeToUtf8(const QString strUnicode)
{
	QString strOut = strUnicode;

	int nPos = 0;
	QRegExp rx("&#x([0-9,a-f|A-F]{4});");

	while ((nPos = rx.indexIn(strOut, nPos)) != -1)
	{
		QChar qCh(rx.cap(1).toUShort(nullptr, 16));
		strOut.replace(nPos, rx.matchedLength(), qCh);
		nPos += 1;
	}

	return strOut;
}

使用代码:

QString str = QString::fromLocal8Bit("5.6破坏的房屋和街区.svg");

QString strUnicode = utf8ToUnicode(str);

QString strUtf8 = unicodeToUtf8(strUnicode);

 

原网站

版权声明
本文为[北极熊的奋斗史]所创,转载请带上原文链接,感谢
https://blog.csdn.net/chenxipu123/article/details/106786483