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

编译: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);
}
复制代码

 

posted @   chinacloudy  阅读(8841)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
历史上的今天:
2014-10-13 据说练就了一指禅神功的觅闻实时手机新闻网,正以每天2000+IP的用户量递增。有智能手机的可以当场进行体验,没有的就算了哈
2014-10-13 据说练就了一指禅神功的觅闻实时手机新闻网,正以每天2000+IP的用户量递增。有智能手机的可以当场进行体验,没有的就算了哈
点击右上角即可分享
微信分享提示