VC中GBK与UTF8字符串的转换(zz)

By Jiang | 10月 24, 2006

作者: 秋梦无痕
链接: http://www.sinzy.net/blog/Read.asp?ID=44&BID=4371

想在VC中把GB2312/GBK字符串转换成UTF8/Unicode字符串,昨天折腾了三个多小时,在google上跑了好几圈,还是没能实现,结果今天早上一过来就搞定了。共享之:

  1. void ConvertGBKToUtf8(CString& strGBK) {
  2. int len=MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, NULL,0);
  3. unsigned short * wszUtf8 = new unsigned short[len+1];
  4. memset(wszUtf8, 0, len * 2 + 2);
  5. MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, wszUtf8, len);
  6. len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);
  7. char *szUtf8=new char[len + 1];
  8. memset(szUtf8, 0, len + 1);
  9. WideCharToMultiByte (CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL,NULL);
  10. strGBK = szUtf8;
  11. delete[] szUtf8;
  12. delete[] wszUtf8;
  13. }
  1. void ConvertUtf8ToGBK(CString& strUtf8) {
  2. int len=MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUtf8, -1, NULL,0);
  3. unsigned short * wszGBK = new unsigned short[len+1];
  4. memset(wszGBK, 0, len * 2 + 2);
  5. MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUtf8, -1, wszGBK, len);
  6. len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
  7. char *szGBK=new char[len + 1];
  8. memset(szGBK, 0, len + 1);
  9. WideCharToMultiByte (CP_ACP, 0, wszGBK, -1, szGBK, len, NULL,NULL);
  10. strUtf8 = szGBK;
  11. delete[] szGBK;
  12. delete[] wszGBK;
  13. }
Topics: 程序设计 | 5,863 views | 关闭评论
LinkWorth
Hostgator

酷站链接 (Featured Links)

最新评论 (Recent Comments)

  • air jordan shoe: 不错,挺厉害的~~
  • Hairstyles: 原来链接这么重要!
  • Haircuts: 有空试一下看看
  • CHI Flat Iron: 哇,这么多插件啊,慢慢看!
  • 诗酒如画: 1)备份你的WordPress数据库 推荐用WordPress Database Backup在后台操作.下载备份的压缩包或者是传到自己邮箱里都可以. 如果直接在数据库中备份的话,记得选择UTF8编码,切记. 2)备份你的程序...
  • north face wholesale: en ,我会试一试的。

搜索 (Search)

合作伙伴

推荐站点 (Recommendations)

Partner links

WordPressChina
  • 原创博客联盟