utf8 和 gb2312 的轉換

  1. int chr2wch(const char* buffer, wchar_t* &wBuf)
  2. {
  3.       size_t len = strlen(buffer);

  4.       size_t wlen = MultiByteToWideChar(CP_ACP, 0, (const char*)buffer, int(len), NULL, 0);

  5.       wBuf = new wchar_t[wlen + 1];

  6.       MultiByteToWideChar(CP_ACP, 0, (const char*)buffer, int(len), wBuf, int(wlen));
  7.      wBuf[wlen] = 0;

  8.      return (int)wlen;
  9. }

  10. int chr2utf(const char* buf, char* &mb_buf)
  11. {
  12.     WCHAR* wbuf;
  13.     int wlen = chr2wch(buf, wbuf);
  14.     int mb_buf_size = ::WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, NULL, 0, NULL, NULL);
  15.     mb_buf = new char[mb_buf_size + 1];
  16.     int mb_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, mb_buf, mb_buf_size, NULL, NULL);        
  17.     mb_buf[mb_len] = 0;
  18.     delete[] wbuf;
  19.     return mb_len;
  20. }


  21. int utf2wch(const char* buffer, wchar_t* &wBuf)
  22. {
  23.     size_t len = strlen(buffer);

  24.     size_t wlen = MultiByteToWideChar(CP_UTF8, 0, (const char*)buffer, int(len), NULL, 0);

  25.     wBuf = new wchar_t[wlen + 1];

  26.     MultiByteToWideChar(CP_UTF8, 0, (const char*)buffer, int(len), wBuf, int(wlen));
  27.     wBuf[wlen] = 0;

  28.     return (int)wlen;
  29. }

  30. int utf2chr(const char* buf, char* &mb_buf)
  31. {
  32.     WCHAR* wbuf;
  33.     int wlen = utf2wch(buf, wbuf);
  34.     int mb_buf_size = ::WideCharToMultiByte(CP_ACP, 0, wbuf, wlen, NULL, 0, NULL, NULL);
  35.     mb_buf = new char[mb_buf_size + 1];
  36.     int mb_len = ::WideCharToMultiByte(CP_ACP, 0, wbuf, wlen, mb_buf, mb_buf_size, NULL, NULL);        
  37.     mb_buf[mb_len] = 0;
  38.     delete[] wbuf;
  39.     return mb_len;
  40. }

 

由於保存新的字符串的內存是堆上創建的,所以用完之後要 delete []out_msg;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章