mfc中如何将多字节编码转为utf8编码

mfc中如何将多字节编码转为utf8编码

新建mfc项目时可选多字节编码(MBCS)或者unicode编码,而有些第三方库用到了utf8编码,此时需要进行编码转换。

以下是将多字节编码转换成utf8的mfc代码,注意CP_ACP和CP_UTF8的使用

string MultiByteToUFT8(const string &str)
{
    int len = MultiByteToWideChar(CP_ACP, NULL, str.c_str(), str.size(), NULL, 0);
    vector<wchar_t> chars(len + 1);
    MultiByteToWideChar(CP_ACP, NULL, str.c_str(), str.size(), chars.data(), len);

    int len2 = WideCharToMultiByte(CP_UTF8, NULL, chars.data(), -1, NULL, NULL, NULL, NULL);
    vector<char> chars2(len2 + 1);
    WideCharToMultiByte(CP_UTF8, 0, chars.data(), -1, chars2.data(), len2, NULL, NULL);

    string str2 = chars2.data();
    return str2;
}

 

posted @ 2022-08-28 21:44  李建业  阅读(501)  评论(0编辑  收藏  举报