GDK和utf-8编码互相转换

本文介绍了一种通用的GBK与UTF-8编码转换方案,适用于Windows和Linux平台。通过提供C语言编写的动态库接口,实现了两种编码之间的相互转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在程序开发中,往往需要进行编码转换。中国的汉字采用的是GBK编码,往往需要转换为utf-8编码。因此,这里给出windows和linux的通用转换方案。接口和实现已经写好,编译出来是个动态库。如有不对地方,请大家指正。

//CCharacter.h file
#ifndef CCHARACTER_H
#define CCHARACTER_H

#include <stddef.h>

#ifdef _WIN32
#       ifdef EXPORT_CHARACTER
#               define CCONVERSION_API extern "C" __declspec( dllexport )
#       else
#               define CCONVERSION_API extern "C" __declspec( dllimport )
#       endif
#else
#       define CCONVERSION_API  extern "C"
#endif

CCONVERSION_API int GbkToUtf8(char *inbuf,size_t inlen,char *outbuf,size_t outlen);
CCONVERSION_API int Utf8ToGbk(char *inbuf,size_t inlen,char *outbuf,size_t outlen);

#endif // CCHARACTER_H
//CCharacter.cpp file
#include "CCharacter.h"
# ifdef WIN32
   #include <Windows.h>
#endif
#include <string.h>
#include <stdio.h>


#ifdef _LINUX
  #include <iconv.h>
#endif

CCONVERSION_API int Utf8ToGbk(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{

    if( inlen > outlen )
        return -1;
#ifdef _LINUX
    iconv_t cd;

    char **pin = &inbuf;
    char **pout = &outbuf;

    cd = iconv_open("gb2312","utf-8");
    if (cd == 0)
        return -1;
    memset(outbuf,0,outlen);
    if (iconv(cd,pin,&inlen,pout,&outlen) == -1)
            return -1;
    iconv_close(cd);
    return 0;
#endif

#ifdef WIN32
    int len = MultiByteToWideChar(CP_UTF8, 0, inbuf, -1, NULL, 0);
    wchar_t* wstr = new wchar_t[len+1];
    memset(wstr, 0, len+1);
    MultiByteToWideChar(CP_UTF8, 0, inbuf, -1, wstr, len);
    len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
    WideCharToMultiByte(CP_ACP, 0, wstr, -1, outbuf, len, NULL, NULL);
    if(wstr) delete[] wstr;
    return 0;

#endif
}

CCONVERSION_API int GbkToUtf8(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
    if( inlen > outlen )
        return -1;
#ifdef _LINUX
    iconv_t cd;

    char **pin = &inbuf;
    char **pout = &outbuf;

    cd = iconv_open("utf-8","gb2312");
    if (cd == 0)
        return -1;
    memset(outbuf,0,outlen);
    if (iconv(cd,pin,&inlen,pout,&outlen) == -1)
            return -1;
    iconv_close(cd);
    return 0;
#endif

#ifdef WIN32
    int len = MultiByteToWideChar(CP_ACP, 0, inbuf, -1, NULL, 0);
    wchar_t* wstr = new wchar_t[len+1];
    memset(wstr, 0, len+1);
    MultiByteToWideChar(CP_ACP, 0, inbuf, -1, wstr, len);
    len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
    WideCharToMultiByte(CP_UTF8, 0, wstr, -1, outbuf, len, NULL, NULL);
    if(wstr) delete[] wstr;
    return 0;
#endif
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值