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

来源:互联网 发布:手机写小说软件 编辑:程序博客网 时间:2024/04/30 00:19
在编程过程中需要对字符串进行不同的转换,特别是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的转换,都需要注意的是在使用字符串后,需要删除字符串指针;这是因为以上两个方法返回的是字符串指针,如果没有删除将会内存泄漏,可别说我没提醒你哦。