When developing applications using ndk, character encoding conversion is sometimes required. Here we use the open source library icon for character encoding conversion. The Code is as follows:
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 );
}
The Code Conversion between UTF-16LE, UTF-8 and GBK is supported here