GBK与Unicode的转换⼀、GBK转换到Unicode编码
std::string Gbk2Unicode(std::string &strValue)
{
std::string strReturn;
unsigned char chTemp;
int nLength = strValue.length()*4+1;
WCHAR *pwchBuf = new WCHAR[nLength];
memset(pwchBuf, 0, sizeof(WCHAR) * nLength);
MultiByteToWideChar(CP_ACP, 0, strValue.c_str(), -1, (LPWSTR)pwchBuf, nLength);
for (size_t i = 0; i < wcslen(pwchBuf); i++)
{
strReturn += "\\u";
chTemp = *((unsigned char*)pwchBuf+i*2+1);
if(chTemp)
{
strReturn += m_clsmyOpenssl.char_to_hex( (unsigned char)(chTemp >> 4) );
strReturn += m_clsmyOpenssl.char_to_hex( (unsigned char)(chTemp % 16) );
}
chTemp = *((unsigned char*)pwchBuf+i*2);
strReturn += m_clsmyOpenssl.char_to_hex( (unsigned char)(chTemp >> 4) );
strReturn += m_clsmyOpenssl.char_to_hex( (unsigned char)(chTemp % 16) );
}
delete[]pwchBuf;
pwchBuf = NULL;
return strReturn;
}
⼆、Unicode转换到GBK编码
std::string Unicode2GBK(std::string &strValue)
{
std::vector<std::string> vcString;
MyTools::SplitString(strValue, "\\u", vcString);
wchar_t* pwBuf = new wchar_t[strValue.length() + 1];
memset(pwBuf, 0, (strValue.length() + 1)* sizeof(wchar_t));
int j(0);
for(std::vector<std::string>::iterator it = vcString.begin(); it != d(); ++it)
{
if (it->empty())
{
continue;
}
unsigned short wcTmp = 0;
unsigned char cTmp = 0;
//因为有中⽂字符混合ASSCII码情况,所以条件为k < it->length()
for(size_t k = 0; k < it->length(); ++k)
unicode字符转中文
{
cTmp = (unsigned char)(*it)[k];
if(cTmp <= '9')//0x30~0x39 即0~9
{
wcTmp |= (cTmp & 0x0f) << (it->length() - k - 1) * 4;
}
else if(cTmp >= 'a')//0x61~7a 即a~z
{
wcTmp |= (cTmp - 0x57) << (it->length() - k - 1) * 4;
}
else//0x41~5a 即A~Z
{
wcTmp |= (cTmp - 0x37) << (it->length() - k - 1) * 4;
}
}
pwBuf[j++] = (wchar_t)wcTmp;
}
char *pDst = new char[strValue.length() + 1];
memset(pDst, 0, (strValue.length() + 1) * sizeof(char));
WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, (char*)pDst, strValue.length() - 1, NULL, NULL);
std::string strRet(pDst);
delete[]pwBuf;
pwBuf= NULL; delete[]pDst; pDst=NULL; return strRet; }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论