C++中ASCII、unicode與Utf8之間的相互轉化
阿新 • • 發佈:2019-01-07
一、windows下轉換方法:
// 當type為CP_ACP時,GBK轉化為UNICODE;當type為CP_UTF8時,UTF8轉化為UNICODE wchar_t* trans(const char * ch, int type = CP_ACP) { int len = MultiByteToWideChar(type, 0, ch, -1, nullptr, 0); wchar_t *str = new wchar_t[len + 1]; wmemset(str, 0, len + 1); MultiByteToWideChar(type, 0, ch, -1, str, len); return str; } // 當type為CP_ACP時,UNICODE轉化為GBK;當type為CP_UTF8時,UNICODE轉化為UTF8 char* trans(const wchar_t * wch, int type = CP_ACP) { int len = WideCharToMultiByte(type, 0, wch, -1, nullptr, 0, nullptr, nullptr); char *str = new char[len + 1]; memset(str, 0, len + 1); WideCharToMultiByte(type, 0, wch, -1, str, len, nullptr, nullptr); return str; }
注意:轉換後的字串,使用之後,需要delete掉。
二、linux下轉換方法:
bool trans(const char *pFromCode,const char *pToCode,const char *pInBuf,size_t iInLen,char *pOutBuf,size_t iOutLen) { //開啟字符集轉換 iconv_t hIconv = iconv_open(pToCode, pFromCode); if (! hIconv) return false; //開始轉換 size_t iRet = iRet = iconv(hIconv, (char **) (&pInBuf), &iInLen, &pOutBuf, &iOutLen); //關閉字符集轉換 iconv_close(hIconv); return (bool)iRet; }
使用方法:
string result = "這是gbk字串";
char ch[255];
memset(ch,'\0',sizeof(ch));
trans("GBK","UTF-8",result.c_str(),result.size(),ch,sizeof(ch));
注意:需要安裝libiconv的開發包,並引入標頭檔案#include "iconv.h"
三、c++11自帶的編碼轉換器,程式碼如下:
#include "stdafx.h" #include <iostream> #include <string> #include <codecvt> using namespace std; using WCHAR_GBK = codecvt_byname<wchar_t, char, mbstate_t>; using WCHAR_UTF8 = codecvt_utf8<wchar_t>; // linux下為"zh_CN.GBK" #define GBK_NAME ".936" int main() { // 定義一個utf8字串 string result = u8"中國人"; // gbk與unicode之間的轉換器 wstring_convert<WCHAR_GBK> cvtGBK(new WCHAR_GBK(GBK_NAME)); // utf8與unicode之間的轉換器 wstring_convert<WCHAR_UTF8> cvtUTF8; // 從utf8轉換為unicode wstring ustr = cvtUTF8.from_bytes(result); // 從unicode轉換為gbk string str = cvtGBK.to_bytes(ustr); cout << str << endl; getchar(); return 0; }