Linux字符串编码转换

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;
memset(outbuf,0,outlen);
if (iconv(cd,pin,&inlen,pout,&outlen)==-1) return -1;
iconv_close(cd);
return 0;
}
//UNICODE码转为GB2312码
int u2g(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen);
}
//GB2312码转为UNICODE码
int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen);
}

char in_utf8[] = "adgdd3ef";
char in_gb2312[] = "正在安装";
char out[OUTLEN];

//unicode码转为gb2312码
printf("unicode-->gb2312 in=%s\n", in_utf8);
u2g(in_utf8,strlen(in_utf8),out,OUTLEN);
out[strlen(in_utf8)] = '\0';
printf("unicode-->gb2312 out=%s\n",out);

//gb2312码转为unicode码
printf("gb2312-->unicode in=%s\n",in_gb2312);
g2u(in_gb2312,strlen(in_gb2312),out,OUTLEN);
out[strlen(in_gb2312)] = '\0';
printf("gb2312-->unicode out=%s\n",out);

测试中 中文转码有问题。。。没时间搞了。先mark

posted @ 2017-01-22 16:03  xiao913  阅读(1393)  评论(0编辑  收藏  举报