多字节编码字符串与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;


 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值