编码转换
#include "iconv.h"
static std::string encode_convert(const char* fromcode, const char* tocode, const char* text)
{
char* tmp = (char*)text;
size_t lenSrc = strlen(tmp);
size_t lenDst = lenSrc * 5;
char* out = (char*)malloc(lenDst);
memset(out, 0, lenDst);
char* pFreeOut = out;
iconv_t cd = iconv_open(tocode, fromcode);
size_t ret = iconv(cd, &tmp, &lenSrc, &out, &lenDst);
if (ret == -1)
{
return "";
}
std::string retStr(pFreeOut);
iconv_close(cd);
free(pFreeOut);
return retStr;
}
static std::string GBK_TO_UTF8(const char* text)
{
if (strlen(text) == 0)
{
return "";
}
return encode_convert("GBK", "UTF-8", text);
}
static std::string UTF8_TO_GBK(const char* text)
{
if (strlen(text) == 0)
{
return "";
}
return encode_convert("UTF-8", "GBK", text);
}
int main()
{
std::string test = "测试";
std::string GBK = UTF8_TO_GBK(test.c_str());
std::cout << ": " << test << std::endl;
std::cout << ": " << GBK << " size:" << GBK.size()<<std::endl;
}