utf8转gbk问题
void CChartsetManager::convertGBKToUtf8(CString& strGBK)
{
USES_CONVERSION;
int nLen = MultiByteToWideChar(CP_ACP, 0, W2A((LPCTSTR)strGBK), -1, NULL,0);
wchar_t *wszUtf8 = new wchar_t[nLen+1];
memset(wszUtf8, 0, (nLen+1)*sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, W2A((LPCTSTR)strGBK), -1, wszUtf8, nLen);
nLen = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);
char *szUtf8=new char[nLen+1];
memset(szUtf8, 0, nLen+1);
WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, szUtf8, nLen, NULL,NULL);
strGBK = szUtf8;
delete[] szUtf8;
delete[] wszUtf8;
}
void CChartsetManager::convertUtf8ToGBK(CString& strUtf8)
{
USES_CONVERSION;
int nLen = MultiByteToWideChar(CP_UTF8, 0, W2A((LPCTSTR)strUtf8), -1, NULL,0);
wchar_t *wszGBK = new wchar_t[nLen+1];
memset(wszGBK, 0, (nLen+1)*sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, W2A((LPCTSTR)strUtf8), -1, wszGBK, nLen);
nLen = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
char *szGBK=new char[nLen+1];
memset(szGBK, 0, nLen+1);
WideCharToMultiByte (CP_ACP, 0, wszGBK, -1, szGBK, nLen, NULL,NULL);
strUtf8 = szGBK;
delete[] szGBK;
delete[] wszGBK;
}
这个是两个我gbk和utf8转换的函数,gbk转utf8能转换正确。但utf8转换gbk当汉字为奇数时候,utf8码转换为gbk,会少掉一个字。
一个gbk为2个字节,而utf8为3个字节,当转换的utf8为奇数字节时候,如何才能正确转换为gbk码?