码迷,mamicode.com
首页 > 编程语言 > 详细

C语言编码转换gb2312 to utf8,utf8 to gb2312 代码,GCC编译,支持Windows、Linux

时间:2017-10-13 10:07:10      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:str   include   clu   string   def   nis   ==   tdd   class   

编译:gcc -o f.exe f.c -liconv

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <iconv.h>
#define OUTLEN 255

main()
{
    char *in_utf8 = "姝e?ㄥ??瑁?";
    char *in_gb2312 = "你是谁";
    char out[OUTLEN];
    int rc; 

    //unicode码转为gb2312码
    rc = u2g(in_utf8,strlen(in_utf8),out,OUTLEN);
    //printf("unicode-->gb2312 out=%sn",out);

    //gb2312码转为unicode码
    rc = g2u(in_gb2312,strlen(in_gb2312),out,OUTLEN);
    printf("gb2312-->unicode out=%sn",out);


}


/*代码转换:从一种编码转为另一种编码*/
int code_convert(char *from_charset,char *to_charset,char *inbuf,int inlen,char *outbuf,int 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,int inlen,char *outbuf,int 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);
}

 

C语言编码转换gb2312 to utf8,utf8 to gb2312 代码,GCC编译,支持Windows、Linux

标签:str   include   clu   string   def   nis   ==   tdd   class   

原文地址:http://www.cnblogs.com/bdccloudy/p/7659308.html

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