码迷,mamicode.com
首页 > 其他好文 > 详细

iconv转换

时间:2019-12-21 20:47:13      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:charset   ons   code   open   char   cas   set   ret   col   

///////////////////////////////////////////////////////
 
#include <iconv.h>
 
#include <stdlib.h>
#include <stdio.h>

int code_convert(char *from_charset,char *to_charset,char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
    iconv_t cd;
    int rc;
    char **pin = &inbuf;
    char **pout = &outbuf;

    cd = iconv_open(to_charset,from_charset);
    if (cd==0) 
        return -1;
    if (iconv(cd,pin,&inlen,pout,&outlen)==-1) 
        return -1;
    iconv_close(cd);
    return 0;
}

// utf8码转为GB2312码
int u2g(char *inbuf,int inlen,char *outbuf,int outlen)
{
    return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen);
}

// GB2312码转为utf8
int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
    return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen);
}

// utf8转为gbk
std::string u2a(const char *inbuf)
{
    int inlen=strlen(inbuf);
    string strRet;
    strRet.resize(inlen*2+2);
    if(code_convert("utf-8","gbk",const_cast<char *>(inbuf),inlen,&strRet[0],strRet.size()))
        return inbuf;
    return strRet;
}

// gbk转为utf8
std::string a2u(const char *inbuf)
{
    int inlen=strlen(inbuf);
    string strRet;
    strRet.resize(inlen*2+2);
    if(code_convert("gbk","utf-8",const_cast<char *>(inbuf),inlen,&strRet[0],strRet.size()))
    return inbuf;
    return strRet;
}

 

iconv转换

标签:charset   ons   code   open   char   cas   set   ret   col   

原文地址:https://www.cnblogs.com/hshy/p/12077889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!