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

1,187 阅读2分钟

在编程过程中需要对字符串进行不同的转换,特别是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的转换,都需要注意的是在使用字符串后,需要删除字符串指针;这是因为以上两个方法返回的是字符串指针,如果没有删除将会内存泄漏。