在使用ndk开发应用程序时,有时需要字符编码转换,这里使用开源库icon进行字符编码转换,代码如下
char * convertString(const char * fromCode, const char * toCode, const char * source)
{
size_t retlen = 0;
size_t inbytesleft = strlen(source);
if (!strncmp(fromCode, "UTF-16LE", 8))
{
inbytesleft = gg_wcslen((unsigned short *)source) * 2;
}
size_t outbytesleft = inbytesleft * 4 + 2;
retlen = outbytesleft;
char * tmp = new char[outbytesleft];
memset(tmp, 0, outbytesleft);
char * inbuf = (char *)source;
char * outbuf = tmp;
iconv_t cd = iconv_open(toCode, fromCode);
size_t errorNo = iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
retlen -= outbytesleft;
if (errorNo == -1)
{
memcpy(tmp, source, inbytesleft);
}
else
{
memset(tmp+retlen, 0, outbytesleft);
}
iconv_close(cd);
return tmp;
}
unsigned short* gbkToUnicode(const char* gbk)
{
return (unsigned short*)convertString("GBK","UTF-16LE",gbk);
}
char* gbkToUtf8(const char* gbk)
{
return convertString("GBK","UTF-8",gbk);
}
char* unicodeToGbk(const unsigned short* unicode)
{
return convertString("UTF-16LE","GBK",(const char*)unicode);
}
char* unicodeToUtf8(const unsigned short* unicode)
{
return convertString("UTF-16LE","UTF-8",(const char*)unicode);
}
unsigned short* utf8ToUnicode(const char* utf8)
{
return (unsigned short*)convertString("UTF-8","UTF-16LE",utf8);
}
char* utf8ToGbk(const char* utf8)
{
return convertString("UTF-8","GBK",utf8);
}
这里支持UTF-16LE,UTF-8和GBK之间的编码相互转换