Linux下C++通过iconv实现字符集UTF8和GBK互转(转)

#include <iconv.h>
#include <iostream>
#include <string.h>
#include <malloc.h>

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

    cd = iconv_open(to_charset, from_charset);
    if (cd == 0)
        return -1;

    memset(outbuf, 0, outlen);

    if ((int)iconv(cd, pin, &inlen, pout, &outlen) == -1)
    {
        iconv_close(cd);
        return -1;
    }
    iconv_close(cd);
    *pout = '\0';

    return 0;
}

int u2g(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {
    return code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, outlen);
}

int g2u(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {
    return code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, outlen);
}

std::string GBKToUTF8(const std::string& strGBK)
{
    int length = strGBK.size()*2+1;

    char *temp = (char*)malloc(sizeof(char)*length);

    if(g2u((char*)strGBK.c_str(),strGBK.size(),temp,length) >= 0)
    {
        std::string str_result;
        str_result.append(temp);
        free(temp);
        return str_result;
    }else
    {
        free(temp);
        return "";
    }
}

std::string UTFtoGBK(const char* utf8)
{
    int length = strlen(utf8);

    char *temp = (char*)malloc(sizeof(char)*length);

    if(u2g((char*)utf8,length,temp,length) >= 0)
    {
        std::string str_result;
        str_result.append(temp);
        free(temp);

        return str_result;
    }else
    {
        free(temp);
        return "";
    }
}

int main()
{
    std::string teststr = "测试字符串";

    std::cout<< "原始字符串:" << teststr.c_str() << std::endl;

    std::cout<< "UTF8转换GBK后的字符串:" << UTFtoGBK(teststr.c_str()).c_str() << std::endl;

    std::cout<< "GBK转换UTF8后的字符串:" << GBKToUTF8(UTFtoGBK(teststr.c_str()).c_str()).c_str() << std::endl;

    getchar();

    return 0;
}
————————————————
版权声明:本文为CSDN博主「Alderaan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/GerZhouGengCheng/article/details/120923984

posted on 2022-05-20 11:07  混元真人  阅读(2791)  评论(0)    收藏  举报