c++中Gb2312与utf8互转函数

const Int CHAR_BUFSIZE = 4096;       /**< 待转换名最大长度*/

  /** GB2312转UTF8,假定pcUtf8已有足够空间*/

  __inline void Gb2312ToUtf8(const char *pcGb2312, std::string & strUtf8)

  {

   //wchar_t pcUnicode[CHAR_BUFSIZE];

   //gb2312 to unicode

   Int nUnicodeLen = MultiByteToWideChar(CP_ACP, 0, pcGb2312, -1, NULL, 0);

   wchar_t * pcUnicode = new wchar_t[nUnicodeLen+1];
   memset(pcUnicode, 0, nUnicodeLen * 2 + 2);

   MultiByteToWideChar(CP_ACP, 0, pcGb2312, -1, pcUnicode, nUnicodeLen);


   //unicode to utf8

   Int nUtf8Len = WideCharToMultiByte(CP_UTF8, 0, pcUnicode, -1, NULL, 0, NULL, NULL);

   char *pcUtf8=new char[nUtf8Len + 1];
   memset(pcUtf8, 0, nUtf8Len + 1);   

   WideCharToMultiByte(CP_UTF8, 0, pcUnicode, -1, pcUtf8, nUtf8Len, NULL, NULL);
  
   strUtf8=pcUtf8;
   delete[] pcUtf8;
   delete[] pcUnicode;
  }

 

  /** UTF8转GB2312,假定pcGb2312已有足够空间*/

  __inline void Utf8ToGb2312(const char *pcUtf8, std::string & strGB2312)

  {

   //wchar_t pcUnicode[CHAR_BUFSIZE];

   Int nUnicodeLen = MultiByteToWideChar(CP_UTF8, 0, pcUtf8, -1, NULL, 0);

   wchar_t * pcUnicode = new wchar_t[nUnicodeLen+1];
   memset(pcUnicode, 0, nUnicodeLen * 2 + 2);

   //utf8 to unicode

   MultiByteToWideChar(CP_UTF8, 0, pcUtf8, -1, pcUnicode, nUnicodeLen);

   //unicode to gb2312

   int nGb2312Len = WideCharToMultiByte(CP_ACP, 0, pcUnicode, -1, NULL, 0, NULL, NULL);

   char *pcGb2312=new char[nGb2312Len + 1];
   memset(pcGb2312, 0, nGb2312Len + 1);

   WideCharToMultiByte(CP_ACP, 0, pcUnicode, -1, pcGb2312, nGb2312Len, NULL, NULL);

   strGB2312=pcGb2312;
   delete[] pcGb2312;
   delete[] pcUnicode;
  }

  __inline std::string StringToUtf8(const std::string& strSource)
  { 
   std::string strTmp="";
   Gb2312ToUtf8(strSource.c_str(),strTmp);   
   return strTmp; 
  }

  __inline std::string StringToGB2312(const std::string& strSource)
  { 
   std::string strTmp="";
   Utf8ToGb2312(strSource.c_str(),strTmp);   
   return strTmp; 
  }

  __inline std::string StringToUtf8(const char * strSource)
  {
   return StringToUtf8(std::string(strSource));
  }

  __inline std::string StringToGB2312(const char * strSource)
  {
   std::string strTmp="";
   Utf8ToGb2312(strSource,strTmp);   
   return strTmp; 
  }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值