C++中GB2312字符串和UTF-8之间的转换 从CString 的转换

时间:2023-01-10 17:37:48


在编程过程中需要对字符串进行不同的转换,特别是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;
}



以及对CString 到char* 和string的转换(unicode下的转换)

std::string ProgressSetup::U2G( CString utf8)

int nLen = WideCharToMultiByte(CP_ACP, 0, utf8, -1, NULL, 0, NULL, NULL);
if (nLen<= 0) return NULL;
char* pszDst = new char[nLen];
if (NULL == pszDst) return NULL;
WideCharToMultiByte(CP_ACP, 0, utf8, -1, pszDst, nLen, NULL, NULL);
std::string str(pszDst);
delete []pszDst;
return str;
}


string 到CString 比较简单

string str="abcde";

CString cstr(str.c_str());

或者CString cstr(str.data());