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

C/C++ 专栏收录该内容
90 篇文章 0 订阅

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
    点赞
  • 1
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值