文章几乎完全学习摘抄自这两篇文章。
(3条消息) qt中的toUtf8, toLatin1, Local8bit编码问题_qt tolatin1_左天任的博客-CSDN博客
(3条消息) 常见的字符编码表_neoyoo/的博客-CSDN博客
1. 常见字符编码:
ASCII码:一个字节,256个字符。
Unicode:字母,汉字都占用两个字节。
utf-8:字母一个字节,汉字3个字节。
gbk:字母一个字节,汉字2个字节。
gb2312:可以表示汉字,gb2312<gbk。
2.出现乱码的原因:
同一段代码采用的编码和解码格式不同。
cmd中编码格式为gbk。
3.好用的网站:汉字字符集编码查询;中文字符集编码:GB2312、BIG5、GBK、GB18030、Unicode (qqxiuzi.cn)
4.Qt中的编码
QString tmp("D:/你");
(1)
QString::toLatin1相当于ascii码
遇到中文默认转换为ascii码0x3f('?') 。
D | : | / | 你(?) |
68 | 58 | 47 | 63 |
0x44 | 0x3a | 0x2f | 0x3f |
printf("toLatin1() \n");
char *p=new char[1+strlen(tmp.toLatin1().data())];
strcpy(p,tmp.toLatin1().data());
for(int i=0;p[i]!='\0';i++)
{
printf("0x%02x \n",(unsigned char)p[i]);
}
toLatin1()
0x44
0x3a
0x2f
0x3f
(2)
QString里面的汉字是UTF-8编码的字符集
QString::toUtf8是输出UTF-8编码的字符集
D | : | / | 你 |
68 | 58 | 47 | 63 |
0x44 | 0x3a | 0x2f | 0xe4bda0 |
printf("toUtf8() \n");
p=new char[1+strlen(tmp.toUtf8().data())];
strcpy(p,tmp.toUtf8().data());
for(int i=0;p[i]!='\0';i++)
{
printf("0x%02x \n",(unsigned char)p[i]);
}
toUtf8()
0x44
0x3a
0x2f
0xe4
0xbd
0xa0
(3)
QString::Local8bit()返回的是本地操作系统设置的字符集编码
怎么查看操作系统设置的字符集编码是什么呢?
windons系统cmd输入chcp,返回936,说明是GB2312编码的字符集,可以查找代码页转换表
printf("toLocal8bit \n");
p=new char[1+strlen(tmp.toLocal8Bit().data())];
strcpy(p,tmp.toLocal8Bit().data());
for(int i=0;p[i]!='\0';i++)
{
printf("0x%02x \n",(unsigned char)p[i]);
}
toLocal8bit
0x44
0x3a
0x2f
0xc4
0xe3
(4)
Utf-8编码
printf("QString \n");
p=new char[1+strlen(tmp.toStdString().c_str())];
strcpy(p,tmp.toStdString().c_str());
for(int i=0;p[i]!='\0';i++)
{
printf("0x%02x \n",(unsigned char)p[i]);
}
QString
0x44
0x3a
0x2f
0xe4
0xbd
0xa0
(5)人为设置编码
QTextCodec *codec =QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForLocale(codec);
toLocal8bit
0x44
0x3a
0x2f
0xe4
0xbd
0xa0
本地编码变为UTF-8。