C++中GB2312字符串和UTF-8之间的转换
发布日期:2021-05-07 14:35:57 浏览次数:22 分类:原创文章

本文共 1134 字,大约阅读时间需要 3 分钟。

/***********************************
函数:Utf8ToGB2312
功能:UTF-8转换为GB2312
************************************/
char* Utf8ToGB2312(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;
        wstr = NULL;
    }
    return str;
}
/***********************************
函数:GB2312ToUtf8
功能:GB2312转换为UTF-8
************************************/
char* GB2312ToUtf8(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;
}

上一篇:mfc 中在对Gdi+ 进行配置之后,编译产生很多error错误
下一篇:VS每次编译都重新编译整个工程解决办法

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年03月22日 10时10分14秒