C++中GB2312字符串和UTF-8之間的轉換


在編程過程中需要對字符串進行不同的轉換,特別是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的轉換,都需要注意的是在使用字符串后,需要刪除字符串指針;

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM