#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;
}
Linux下C++通过iconv实现字符集UTF8和GBK互转
最新推荐文章于 2024-02-21 19:33:38 发布