Ucs和Utf8的互转

1:Ucs转成Utf8

 

BOOL CCommenDlg::UcsToUtf8(const CStringW &strUcs, CStringA &strUtf8)
{// Ucs 转换为 Utf8  int iRet = ::WideCharToMultiByte(CP_UTF8, 0, strUcs, -1, NULL, 0, NULL, NULL);  if (iRet == 0)  return FALSE;  CHAR *szBuf = new CHAR[iRet];  iRet = ::WideCharToMultiByte(CP_UTF8, 0, strUcs, -1, szBuf, iRet, NULL, NULL);  if (iRet == 0)  return FALSE;  strUtf8 = szBuf;  delete [] szBuf;  return TRUE;  
}

下面是string的unicode字符串  --->> string的utf8字符串

std::string CCommenDlg::UnicodeToUtf8(std::string strSrc)
{int nwLen = ::MultiByteToWideChar(CP_ACP, 0, strSrc.c_str(), -1, NULL, 0);wchar_t *pwBuf = new wchar_t[nwLen + 1];ZeroMemory(pwBuf, nwLen * 2 + 2);::MultiByteToWideChar(CP_ACP, 0, strSrc.c_str(), strSrc.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 sResult(pBuf);delete[] pwBuf;delete[] pBuf;pwBuf = nullptr;pBuf = nullptr;return sResult;
}


2:Utf8转成Ucs

 

 

BOOL CCommenDlg::Uft8ToUcs(const CStringA &strUtf8, CStringW &strUcs)
{// Utf8 转换为 Unicode  int iRet = ::MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, NULL, 0);  if (iRet == 0)  return FALSE;  WCHAR *szBuf = new WCHAR[iRet];  iRet = ::MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, szBuf, iRet);  if (iRet == 0)  return FALSE;  strUcs = szBuf;  delete [] szBuf;  return TRUE;  
}

下面是string的utf8字符串  --->> string的unicode字符串

std::string CCommenDlg::Utf8ToUnicode(std::string strSrc)
{int nwLen = MultiByteToWideChar(CP_UTF8, 0, strSrc.c_str(), -1, NULL, 0);wchar_t * pwBuf = new wchar_t[nwLen + 1];memset(pwBuf, 0, nwLen * 2 + 2);MultiByteToWideChar(CP_UTF8, 0, strSrc.c_str(), strSrc.length(), pwBuf, nwLen);int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);char * pBuf = new char[nLen + 1];memset(pBuf, 0, nLen + 1);WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);std::string retStr = pBuf;delete[]pBuf;delete[]pwBuf;pBuf = NULL;pwBuf = NULL;return retStr;
}

 

 

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部