C++中文内码的转换方法


C++ #中文2014-04-25 09:58
转换涉及到的 API 函数主要有两个:MultiByteToWideChar 和 WideCharToMultiByte。有关这两个函数的详细文档请参考 MSDN,本文不再赘述。


  本文将介绍四个转换函数分别实现如下的转换:


    * Big5 => GBK
    * GBK => Big5
    * GB2312 => GBK
    * GBK => GB2312


  有关 GB2312 =〉BIG5 的转换以及 BIG5 =〉GB2312 的转换可以通过 GBK 间接实现。先将 GB2312 转成 GBK,再将 GBK 转成 BIG5,反之亦然。当然也可以自己实现它们之间的直接转换。


// Big5 => GBK:


void BIG52GBK(char *szBuf)
{
  if(!strcmp(szBuf, ""))
   return;
  int nStrLen = strlen(szBuf);
  wchar_t *pws = new wchar_t[nStrLen + 1];
  try
  {
   int nReturn = MultiByteToWideChar(950, 0, szBuf, nStrLen, pws, nStrLen + 1);
   BOOL bValue = false;
   nReturn = WideCharToMultiByte(936, 0, pws, nReturn, szBuf, nStrLen + 1, "?", &bValue);
   szBuf[nReturn] = 0;
  }
  __finally
  {
   delete[] pws;
  }
}


//---------------------------------------------------------------------------
// GBK => Big5


void GBK2BIG5(char *szBuf)
{
  if(!strcmp(szBuf, ""))
   return ;
  int nStrLen = strlen(szBuf);
  wchar_t *pws = new wchar_t[nStrLen + 1];
  __try
  {
   MultiByteToWideChar(936, 0, szBuf, nStrLen, pws, nStrLen + 1);
   BOOL bValue = false;
   WideCharToMultiByte(950, 0, pws, nStrLen, szBuf, nStrLen + 1, "?", &bValue);
   szBuf[nStrLen] = 0;
  }
  __finally
  {
   delete[] pws;
  }
}




//----------------------------------------------------------------------------
// GB2312 => GBK
void GB2GBK(char *szBuf)
{
  if(!strcmp(szBuf, ""))
   return;
  int nStrLen = strlen(szBuf);
  WORD wLCID = MAKELCID(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED), SORT_CHINESE_PRC);
  int nReturn = LCMapString(wLCID, LCMAP_TRADITIONAL_CHINESE, szBuf, nStrLen, NULL, 0);
  if(!nReturn)
   return;
  char *pcBuf = new char[nReturn + 1];
  __try
  {
   wLCID = MAKELCID(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED), SORT_CHINESE_PRC);
   LCMapString(wLCID, LCMAP_TRADITIONAL_CHINESE, szBuf, nReturn, pcBuf, nReturn + 1);
   strncpy(szBuf, pcBuf, nReturn);
  }
  __finally
  {
   delete[] pcBuf;
  }
}
//---------------------------------------------------------------------------
// GBK =〉GB2312


void GBK2GB(char *szBuf)
{
  if(!strcmp(szBuf, ""))
   return;
  int nStrLen = strlen(szBuf);
  WORD wLCID = MAKELCID(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED), SORT_CHINESE_BIG5);
  int nReturn = LCMapString(wLCID, LCMAP_SIMPLIFIED_CHINESE, szBuf, nStrLen, NULL, 0);
  if(!nReturn)
   return;
  char *pcBuf = new char[nReturn + 1];
  __try
  {
   wLCID = MAKELCID(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED), SORT_CHINESE_BIG5);
   LCMapString(wLCID, LCMAP_SIMPLIFIED_CHINESE, szBuf, nReturn, pcBuf, nReturn + 1);
   strncpy(szBuf, pcBuf, nReturn);
  }
  __finally
  {
   delete []pcBuf;
  }
}




// 调用示例


   ......


  char sourceEncode[255];
  char szBuf[1024];


  // 从 GB2312 转到 GBK
  strcpy(szBuf, sourceEncode);
  GB2GBK(szBuf);


  // 从GB2312 转到 BIG5,通过 GBK 中转
  strcpy(szBuf, sourceEncode);
  GB2GBK(szBuf);
  GBK2BIG5(szBuf);
   
   ......


}  

相关文章

粤ICP备11097351号-1