1、通过Python3示例探索常用字符串编码
下面,我们通过Python3代码来了解一下字符串编码的小秘密:
首先,我们定义一个字符串aha123
aha123 = "啊哈123"
然后,我们看看它在各种编码下的二进制:
UTF8
aha123.encode('utf8')
b'\xe5\x95\x8a\xe5\x93\x88123'
ANSI
aha123.encode('gbk')
b'\xb0\xa1\xb9\xfe123'
Unicode
aha123.encode('unicode_escape')
b'\\u554a\\u54c8123'
小结
计算机中储存的信息都是用二进制数表示的;而我们在屏幕上看到的英文、汉字等字符是二进制数转换之后的结果。通俗的说,按照何种规则将字符存储在计算机中,如'a'用什么表示,称为"编码";反之,将存储在计算机中的二进制数解析显示出来,称为"解码",如同密码学中的加密和解密。在解码过程中,如果使用了错误的解码规则,则导致'a'解析成'b'或者乱码。[1]
从上面的代码可以看出,编码是一种映射方式,它将字符串转换成了不同的二进制值,其中
gbk,utf8
对应于(unsigned )char[-128,128] [0,255]
;\(f:string \to uchar\)unicode
对应于(unsigned )short[-32768,32768] [0,65535]
;;\(f:string \to ushort\)
def dump_content_codings(content):
print('原文 :',content)
print('utf8 :', content.encode('utf8'))
print('gbk :', content.encode('gbk'))
print('unicode:', content.encode('unicode_escape'))
dump_content_codings('aha123')
dump_content_codings(aha123)
原文 : aha123
utf8 : b'aha123'
gbk : b'aha123'
unicode: b'aha123'
原文 : 啊哈123
utf8 : b'\xe5\x95\x8a\xe5\x93\x88123'
gbk : b'\xb0\xa1\xb9\xfe123'
unicode: b'\\u554a\\u54c8123'
2、Qt5中使用QTextCodec进行编码转换
Qt使用Unicode来存储、绘制和操作字符串。
Qt提供了一组QTextCodec类来帮助在Unicode和非Unicode格式之间进行转换。您还可以创建自己的编解码器类。[2]
void string_coding_test() {
std::string aha_u8 = u8"啊哈123";
QTextCodec* utf8_codec = QTextCodec::codecForName("UTF-8");
QTextCodec* gbk_codec = QTextCodec::codecForName("GBK");
// UTF8 -> Unicode,首先将utf8转换成内置的unicode(QString)
QString aha_unicode = utf8_codec->toUnicode(aha_u8.c_str());
// Unicode -> gbk,再从unicode转换成gbk
std::string aha_gbk = gbk_codec->fromUnicode(aha_unicode);
// 以下代码用于显示转换后的二制内容以及保存的文本文件内容
for (auto& i : aha_gbk)
{
if ('0' <= i && i <= '9')
std::cout << i;
else
std::cout << "\\x" << std::hex << short(i);
}
std::cout << std::endl ;
{
std::string sPath = "text_gbk.txt";
std::ofstream file(sPath);
file << aha_gbk << std::endl;
}
// Unicode -> utf8,又从unicode转换成utf-8
std::string aha_u8_2 = utf8_codec->fromUnicode(aha_unicode);
// 以下代码用于显示转换后的二制内容以及保存的文本文件内容
for (auto& i : aha_u8_2)
{
if ('0' <= i && i <= '9')
std::cout << i;
else
std::cout << "\\x" << std::hex << short(i);
}
{
std::string sPath = "text_u8.txt";
std::ofstream file(sPath);
file << aha_u8 << std::endl;
}
}
小结
在Qt5中,先将字符串保存为QString(Unicode),然后,再通过QTextCodec,将Unicode转换成其它编码的字符串。