字符编码转化 - daniel_yao的专栏 - CSDNBlog

来源:百度文库 编辑:神马文学网 时间:2024/04/29 01:23:41
 字符编码转化    
bool GB2312_AnsiToUnicode(char *lpszOut, const char* lpszIn,
const char* lpszCurCode/* = NULL*/,
const char* lpszOutCode/* = NULL*/)
{
#ifdef WIN32       //  _WIN32
//Do nothing
int lpszOut_size=GB2312_AnsiToUnicode_Size(lpszIn);
//这函数与操作系统相关,XP下用CP_THREAD_ACP,win2000下用CP_ACP
MultiByteToWideChar(CP_THREAD_ACP, 0,lpszIn,strlen(lpszIn)+1,(unsigned short*)lpszOut,lpszOut_size);
#else               //  _WIN32
#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);
#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;
}
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1785300