UTF8及GBK互转时含奇数汉字或混合时不正确,请高手指教解决方案
UTF8及GBK互转时含奇数汉字或混合时不正确,请高手指教
//我现在要实现GBK和UTF8的互转,写了下面的函数,发现中文字符为奇数个或字母汉字混合时编码不正确 ,弄昏了,请高人指点一下
//调用方法为Convert(strFrom,936,CP_UTF8);Convert(strFrom,CP_UTF8,936);
CAtlString Convert(CAtlString strSrc, int sourceCodepage, int targetCodepage)
{
//先将字符串转换为指定CODEPAGE的UNICODE编码
int unicodeLen=MultiByteToWideChar(sourceCodepage,0,strSrc.GetBuffer(),-1,NULL,0);
LPWSTR pUnicode=new wchar_t[unicodeLen+1];
memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));
MultiByteToWideChar(sourceCodepage,0,strSrc.GetBuffer(),-1,pUnicode,unicodeLen+1);
//然后将UNICODE编码转换为指定CODEPAGE的多字节编码
int targetLen=WideCharToMultiByte(targetCodepage,0,pUnicode,-1,NULL,0,NULL,NULL);
CHAR * pTargetData=new CHAR[targetLen+1];
memset(pTargetData,0,targetLen+1);
WideCharToMultiByte(targetCodepage,0,pUnicode,-1,pTargetData,targetLen+1,NULL,NULL);
CString retStr= " ";
retStr.Format( "%s ",pTargetData);
delete[] pUnicode;
pUnicode=NULL;
delete[] pTargetData;
pTargetData =NULL;
return retStr;
} ;
------解决方案--------------------
试试base64编码后再传
byte和char的互换经常会出现这样的错误
//我现在要实现GBK和UTF8的互转,写了下面的函数,发现中文字符为奇数个或字母汉字混合时编码不正确 ,弄昏了,请高人指点一下
//调用方法为Convert(strFrom,936,CP_UTF8);Convert(strFrom,CP_UTF8,936);
CAtlString Convert(CAtlString strSrc, int sourceCodepage, int targetCodepage)
{
//先将字符串转换为指定CODEPAGE的UNICODE编码
int unicodeLen=MultiByteToWideChar(sourceCodepage,0,strSrc.GetBuffer(),-1,NULL,0);
LPWSTR pUnicode=new wchar_t[unicodeLen+1];
memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));
MultiByteToWideChar(sourceCodepage,0,strSrc.GetBuffer(),-1,pUnicode,unicodeLen+1);
//然后将UNICODE编码转换为指定CODEPAGE的多字节编码
int targetLen=WideCharToMultiByte(targetCodepage,0,pUnicode,-1,NULL,0,NULL,NULL);
CHAR * pTargetData=new CHAR[targetLen+1];
memset(pTargetData,0,targetLen+1);
WideCharToMultiByte(targetCodepage,0,pUnicode,-1,pTargetData,targetLen+1,NULL,NULL);
CString retStr= " ";
retStr.Format( "%s ",pTargetData);
delete[] pUnicode;
pUnicode=NULL;
delete[] pTargetData;
pTargetData =NULL;
return retStr;
} ;
------解决方案--------------------
试试base64编码后再传
byte和char的互换经常会出现这样的错误