C/C++笔记(04):GB2312字符串和UTF-8之间的转换

在编程过程当中须要对字符串进行不一样的转换,特别是Gb2312和Utf-8直接的转换。
编程

在几个开源的魔兽私服中,不少都是国外开发的,而暴雪为了可以兼容世界上的各个字符集也使用了UTF-8。在中国使用VS(VS2005以上版本)开发基本都是使用Gb2312的Unicode字符集,因此当在编程过程当中就须要进行字符转换,这样才能兼容游戏,不然就是乱码。而在控制台显示字符串时,正好相反须要将UTF-8的字符串转换成Gb2312才能正常显示。
bash

为了解决这个问题,转换以下;其实不少地方均可以使用到字符串的编码转换,代码以下:ide

// 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的转换,都须要注意的是在使用字符串后,须要删除字符串指针;这是由于以上两个方法返回的是字符串指针,若是没有删除将会内存泄漏。ui

相关文章
相关标签/搜索