Linux C++ gbk转为utf-8

2 篇文章 0 订阅

linux下没有上面的两个函数,需要使用函数 mbstowcs和wcstombs

mbstowcs将多字节编码转换为宽字节编码

wcstombs将宽字节编码转换为多字节编码

这两个函数,转换过程中受到系统编码类型的影响,需要通过设置来设定转换前和转换后的编码类型。通过函数setlocale进行系统编码的设置。

linux下输入命名

locale -a查看系统支持的编码类型。

andy@andy-linux:~$ locale -a
c
en_ag
en_au.utf8
en_bw.utf8
en_ca.utf8
en_dk.utf8
en_gb.utf8
en_hk.utf8
en_ie.utf8
en_in
en_ng
en_nz.utf8
en_ph.utf8
en_sg.utf8
en_us.utf8
en_za.utf8
en_zw.utf8
posix
zh_cn.gb18030
zh_cn.gbk
zh_cn.utf8
zh_hk.utf8
zh_sg.utf8
zh_tw.utf8

本例子中实现的是由zh_CN.gbk到zh_CN.utf8的转换

流程:

1、调用函数setlocale(LC_ALL,"zh_CN.gbk"),设置待转码的字符串类型为gbk类型。

2、调用函数mbstowcs,实现 1  设置的编码到unicode编码的转换。

3、调用函数setlocale(LC_ALL,"zh_CN.utf8"),设置转换后编码类型为utf8类型。

4、调用函数wcstombs,实现unicode到 设置的编码类型的转换。
下面是我写的源码

</pre><pre name="code" class="cpp">#include <stdlib.h>
#include <locale.h>
/******************************************************************************
 * function: gbk2utf8
 * description: 实现由gbk编码到utf8编码的转换 
 * 
 * input: utfstr,转换后的字符串;  srcstr,待转换的字符串; maxutfstrlen, utfstr的最
            大长度
 * output: utfstr
 * returns: -1,fail;>0,success
 * 
 * modification history
 * --------------------
 *  2011-nov-25, lvhongya written
 * --------------------
 ******************************************************************************/
int gbk2utf8(char *utfstr,const char *srcstr,int maxutfstrlen)
{
    if(null==srcstr)
    {
        printf("bad parameter\n");
        return -1;
    }
    //首先先将gbk编码转换为unicode编码
    if(null==setlocale(lc_all,"zh_cn.gbk"))//设置转换为unicode前的码,当前为gbk编码
    {
        printf("bad parameter\n");
        return -1;
    }
    int unicodelen=mbstowcs(null,srcstr,0);//计算转换后的长度
    if(unicodelen<=0)
    {
        printf("can not transfer!!!\n");
        return -1;
    }
    wchar_t *unicodestr=(wchar_t *)calloc(sizeof(wchar_t),unicodelen+1);
    mbstowcs(unicodestr,srcstr,strlen(srcstr));//将gbk转换为unicode
    
    //将unicode编码转换为utf8编码
    if(null==setlocale(lc_all,"zh_cn.utf8"))//设置unicode转换后的码,当前为utf8
    {
        printf("bad parameter\n");
        return -1;
    }
    int utflen=wcstombs(null,unicodestr,0);//计算转换后的长度
    if(utflen<=0)
    {
        printf("can not transfer!!!\n");
        return -1;
    }
    else if(utflen>=maxutfstrlen)//判断空间是否足够
    {
        printf("dst str memory not enough\n");
        return -1;
    }
    wcstombs(utfstr,unicodestr,utflen);
    utfstr[utflen]=0;//添加结束符
    free(unicodestr);
    return utflen;


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值