多字节编码字符串与UTF8字符编码的转换

1、多字节编码字符串转UTF8字符编码

std::string CSqliteDBManager::To_UTF8(std::string strData)
{
	//把GB2312编码的中文字串转换为UTF-8编码的中文字串
	int iLen = strData.length();
	CHAR* pMb = new CHAR[iLen + 1];
	int iMbLen = iLen + 1;
	ZeroMemory(pMb, iMbLen);
	memcpy_s(pMb, iMbLen, strData.c_str(), strData.length());

	//将多字节字符串编码转换成宽字符串
	iLen = ::MultiByteToWideChar(CP_ACP, 0, pMb, iMbLen, NULL, 0);
	WCHAR* lpszW = NULL;
	lpszW = new WCHAR[iLen];
 	::wmemset(lpszW, 0, iLen);

	int iRtn = ::MultiByteToWideChar(CP_ACP, 0, pMb, iMbLen, lpszW, iLen);
	if(iRtn != iLen)
	{	
		delete[] pMb;pMb= NULL;
		delete[] lpszW;lpszW = NULL;		
		return NULL;
	}
	//转换一个宽字符串到UTF8字符串
	int iUTF8Len = ::WideCharToMultiByte(CP_UTF8, 0, lpszW, iLen, NULL, 0, NULL, NULL);
	if(0 == iUTF8Len)
	{
		delete[] pMb;pMb= NULL;<pre class="cpp" name="code">		delete[] lpszW;lpszW = NULL;

		return NULL;
	}

	char* pUTF8 = new char[iUTF8Len];
	::memset(pUTF8, 0, iUTF8Len);
	::WideCharToMultiByte(CP_UTF8, 0, lpszW, iLen, pUTF8, iUTF8Len, NULL, NULL);

	delete[] pMb;pMb= NULL;<pre class="cpp" name="code">	delete[] lpszW;lpszW = NULL;
	delete[] pUTF8;pUTF8= NULL;

	std::string strTemp = pUTF8;
    	return strTemp;
}
 
 

 

2、UTF8字符编码转多字节字符编码

					/*将UTF8字符转换成多字节编码字串*/
					//将UTF8字串转成宽字符字串
					int utf8Len = strlen(pTempElem->GetText<span style="color:#009900;"><span style="color:#000000;">());</span>//pTempElem->GetText()返回的是utf8字符编码字串
</span>					int iLen = MultiByteToWideChar(CP_UTF8, 0, pTempElem->GetText(), utf8Len, NULL, 0);
					WCHAR* lpszW = NULL;
					lpszW = new WCHAR[iLen];
					wmemset(lpszW, 0, iLen);

					int iRtn = MultiByteToWideChar(CP_UTF8, 0, pTempElem->GetText(), utf8Len, lpszW, iLen);
					if(iRtn != iLen)
					{
						delete[] lpszW;
						return;
					}
					//转换宽字符字串到多字节字符串
					int iMBLen = WideCharToMultiByte(CP_ACP, 0, lpszW, iLen, NULL, 0, NULL, NULL);
					if(0 == iMBLen)
					{
						OutputDebugString(_T("Convert failded!"));
						return;
					}
					char* pMBStr = new char[iMBLen];
					::memset(pMBStr, 0, iMBLen); 
					iRtn = WideCharToMultiByte(CP_ACP, 0, lpszW, iLen, pMBStr, iMBLen, NULL, NULL);
					delete[] lpszW;
					if(iRtn != iMBLen)
					{
						OutputDebugString(_T("Convert failded!"));
						return;
					}
	
					string strDataTem = pMBStr;


 

你可能感兴趣的:(utf-8,字符编码转换,ASSIC)