C++字符编码转化代码,大家可以自己编译下看看。
bool GB2312_AnsiToUnicode(char *lpszOut, const char* lpszIn, //这函数与操作系统相关,XP下用CP_THREAD_ACP,win2000下用CP_ACP #else // _WIN32
const char* lpszCurCode/* = NULL*/,
const char* lpszOutCode/* = NULL*/)
{
#ifdef WIN32 // _WIN32
//Do nothing
int lpszOut_size=GB2312_AnsiToUnicode_Size(lpszIn);
MultiByteToWideChar(CP_THREAD_ACP, 0,lpszIn,strlen(lpszIn)+1,(unsigned short*)lpszOut,lpszOut_size);
#ifdef HAVE_ICONV
/* Use iconv to convert the message into utf-16.
* \"char\" and \"\" are aliases for the local 8-bit encoding */
iconv_t cd;
// ICONV_CONST char *from_str = message;
char *from_str = (char*)lpszIn;
char *to_str = lpszOut;
size_t from_sz = strlen(lpszIn) + 1;
// size_t to_sz = from_sz*4;
size_t to_sz = GB2312_AnsiToUnicode_Size(lpszIn);
size_t res;
int i;
char lpszCodeName_From[30], lpszCodeName_To[30];
if (lpszCurCode)
strcpy(lpszCodeName_From, lpszCurCode);
else
strcpy(lpszCodeName_From, \"gb2312\");
if (lpszOutCode)
strcpy(lpszCodeName_To, lpszOutCode);
else
strcpy(lpszCodeName_To, \"UTF-16\");
#ifdef _DEBUG
fprintf(stdout, \"Convert ’%s’ from %s to %s\\n\", lpszIn, lpszCodeName_From, lpszCodeName_To); [Page]
#endif
// if ((cd = iconv_open(\"unicode\", \"gb2312\")) == (iconv_t)-1) {
if ((cd = iconv_open(lpszCodeName_To, lpszCodeName_From)) == (iconv_t)-1) {
perror(\"Couldn’t open iconv\");
return false;
}
res = iconv(cd, &from_str, &from_sz, &to_str, &to_sz);
if (res == -1) {
perror(\"Couldn’t use iconv\");
return false;
}
iconv_close(cd);
#endif
#ifdef _DEBUG
fprintf(stdout, \"Convert result: ’%s’\\n\", lpszOut);
#endif
#endif // End of _WIN32
return true;
}
int GB2312_AnsiToUnicode_Size(const char* lpszIn)
{
int iCounter = 0;
for (int index = 0; lpszIn[index]; index++) {
if( (unsigned char)lpszIn[index] > 127 )
{
index++;
}
else
{
;
}
iCounter+=2;
}
iCounter += 4;
#ifdef _DEBUG
fprintf(stdout, \"GB2312_AnsiToUnicode_Size() return %d\\n\", iCounter);
#endif
return iCounter;
// return 48;
}
C++字符编码转化代码
内容版权声明:除非注明,否则皆为本站原创文章。