您的位置:首页 > 其它

ANSI与UTF8之间的转换!std::string与UTF8之间的转换

2015-05-26 13:26 477 查看
具体思路是先将ANSI转换为UNICODE,再将UNICODE转换为UTF8!

bool CodePageConvert(const char* pIn, char* pOut, int sourceCodepage, int targetCodepage)

{
int sourceLen = MultiByteToWideChar(sourceCodepage, 0, pIn, -1, NULL, 0);
if (sourceLen <= 0)
{
return false;
}

wchar_t* pUnicode = NULL;
pUnicode = new wchar_t[sourceLen+1];
memset(pUnicode, 0, (sourceLen+1)*sizeof(wchar_t));
MultiByteToWideChar(sourceCodepage, 0, pIn,-1, (LPWSTR)pUnicode, sourceLen);

BYTE * pTargetData = NULL;
int targetLen = WideCharToMultiByte(targetCodepage, 0, (LPWSTR)pUnicode, -1, (char *)pTargetData, 0, NULL, NULL);
if (targetLen <= 0)
{
return false;
}

pTargetData = new BYTE[targetLen+1];
memset(pTargetData, 0, targetLen+1);
WideCharToMultiByte(targetCodepage, 0, (LPWSTR)pUnicode, -1, (char *)pTargetData, targetLen, NULL, NULL);

strcpy_s(pOut, targetLen, (char*)pTargetData);

delete [] pTargetData;
delete [] pUnicode;

return true;

}

bool UTF82ANSI(const char* pIn, char* pOut)

{
return CodePageConvert(pIn, pOut, CP_UTF8, CP_ACP);

}

bool ANSI2UTF8(const char* pIn, char* pOut)

{
return CodePageConvert(pIn, pOut, CP_ACP, CP_UTF8);

}

std::string string2UTF8(const std::string & str) 


int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0); 

wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴 
ZeroMemory(pwBuf, nwLen * 2 + 2); 

::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen); 

int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL); 

char * pBuf = new char[nLen + 1]; 
ZeroMemory(pBuf, nLen + 1); 

::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL); 

std::string retStr(pBuf); 

delete []pBuf; 
pBuf  = NULL; 

delete []pwBuf; 
pwBuf = NULL; 

return retStr; 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: