1. 程式人生 > >C++中GB2312字串和UTF-8之間的轉換-json中文亂碼問題

C++中GB2312字串和UTF-8之間的轉換-json中文亂碼問題

在程式設計過程中需要對字串進行不同的轉換,特別是Gb2312和Utf-8直接的轉換。在幾個開源的魔獸私服中,很多都是老外開發的,而暴雪為了能 夠相容世界上的各個字符集也使用了UTF-8。在中國使用VS(VS2005以上版本)開發基本都是使用Gb2312的Unicode字符集,所以當在編 程過程中就需要進行字元轉換,這樣才能相容遊戲,否則就是亂碼。而在控制檯顯示字串時,真好相反需要將UTF-8的字串轉換成Gb2312才能正常顯 示。

為了解決這個問題,本人將其程式碼貼出來;其實很多地方都可以使用到字串的編碼轉換,程式碼如下:

//UTF-8到GB2312的轉換
char* U2G(const char* utf8)
{
int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len+1];
memset(wstr, 0, len+1);
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len+1];
memset(str, 0, len+1);
WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
if(wstr) delete[] wstr;
return str;
}

//GB2312到UTF-8的轉換
char* G2U(const char* gb2312)
{
int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len+1];
memset(wstr, 0, len+1);
MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len+1];
memset(str, 0, len+1);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
if(wstr) delete[] wstr;
return str;
}

無論是GB2312到UTF-8的轉換,還是UTF-8到GB2312的轉換,都需要注意的是在使用字串後,需要刪除字串指標;