Qt与编码

文章几乎完全学习摘抄自这两篇文章。

(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:/你(?)
68584763
0x440x3a0x2f0x3f
    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:/
68584763
0x440x3a0x2f0xe4bda0
    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。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值