欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

三个常见中文内码的转换技巧

最编程 2024-08-13 22:37:33
...
// 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);

......

}

推荐阅读