字符编码转换(UTF8,UNICOD,GB2312。。。。。互相转换)

来源:互联网 发布:超极本推荐2017知乎 编辑:程序博客网 时间:2024/05/22 19:29


#pragma once

//字符转换成BYTE
static BYTE char2byte(char c)
{
 if('0'<=c && c<='9')
 {
  return (c-'0');
 }
 else if('a'<=c && c<='f')
 {
  return (c-'a') + 10 ;
 }
 else if('A'<=c && c<='F')
 {
  return (c-'A') + 10;
 }
 else
 {
  return -1;
 }
}

//组合字节
static BYTE MakeByte(char hichar, char lochar)
{
 BYTE hibyte = char2byte(hichar);
 BYTE lobyte = char2byte(lochar);
 if(hibyte == -1 || lobyte == -1)
  return -1;

 return hibyte << 4 | lobyte;
}

//16进制字符转换成字符
static char whex2char(BYTE n)
{
 if ( 0 <= n && n <= 9 )
 {
  return char('0' + n );
 }
 else if ( 10 <= n && n <= 15 )
 {
  return char('A' + n - 10 );
 }

 return char(0);
}

//字符串转换成16进制字符
static std::string string_to_hex(CString& strTmp)
{
 int nstrlen = strTmp.GetLength();

 std::string strRet;
 strRet.resize(nstrlen * 3);

 int nseq = 0;
 for(int n = 0; n < nstrlen; n += 2)
 {
  BYTE byteRet = MakeByte(strTmp.GetAt(n), strTmp.GetAt(n + 1));
  if(byteRet == -1)
  {
   strRet = " ";
   break;
  }
  strRet[nseq++] = byteRet;
 }

 return strRet;
}

//UTF8转换成16进制字符串
static std::wstring utf8_to_hexstring(std::string& strdata)
{
 int nstrlen = strdata.length();
 //int ntmplen = nstrlen % 3;
 //if(ntmplen > 0)
 // nstrlen -= 1;

 std::wstring wstrout;

 int i = 0;
 TCHAR buff[10] = {0};
 for(i = 0; i < nstrlen - 1; )
 {
  if(strdata.at(i) >= 0 && strdata.at(i) <= 127 )//不是全角字符?
  {
   swprintf(buff, _T("%02X"), strdata.at(i) & 0xFF);
   wstrout += buff;
   i += 1;
  }
  else
  {
   swprintf(buff, _T("%02X"), MAKEWORD(strdata.at(i + 1), strdata.at(i)));
   wstrout += buff;
   i += 2;
  }
 }
 if(i < nstrlen)
 {
  swprintf(buff, _T("%02X"), strdata.at(i) & 0xFF);
  wstrout += buff;
 }

 return wstrout;
}

//UTF8转换成UNICODE
static std::wstring utf8_to_unicode(const std::string& strdata)
{
 std::wstring wstrdata;
 if (strdata.size() == 0)
  return L"";

 wstrdata.resize(strdata.size() * 2);

 int nretcode = MultiByteToWideChar(CP_UTF8, 0, strdata.c_str(), strdata.length(), &wstrdata[0], wstrdata.size());

 if (nretcode > 0)
  wstrdata.resize(nretcode);

 return wstrdata;
}

//UNICODE转换成UTF8
static std::string unicode_to_utf8(const std::wstring& wstrdata)
{
 std::string strdata;
 if (wstrdata.size() == 0)
  return strdata;

 strdata.resize(wstrdata.size()*3);

 int nretcode = WideCharToMultiByte(CP_UTF8, 0, &wstrdata[0], wstrdata.length(), &strdata[0], strdata.size(), 0, 0 );

 if (nretcode > 0)
  strdata.resize(nretcode);

 return strdata;
}

//GB2312转换成UTF8字符串
static std::wstring gb2312_to_utf8string(CString& strTmp)
{
 std::string strutf8 = unicode_to_utf8((LPTSTR)(LPCTSTR)strTmp);

 return utf8_to_hexstring(strutf8);
}

//UTF8字符串转换成GB2312
static std::wstring utf8string_to_gb2312(CString& strTmp)
{
 std::string strutf8 = string_to_hex(strTmp);

 return ::utf8_to_unicode(strutf8);
}

0 0
原创粉丝点击