ANSI與UTF8之間的轉換!std::string與UTF8之間的轉換

shaderdx發表於2015-05-26

具體思路是先將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; 

相關文章