首页 > 其他分享 >编码转换

编码转换

时间:2023-03-17 14:48:50浏览次数:28  
标签:std 编码 转换 src len result str CP

#include <wincodec.h>
#include <winnt.h>

std::string unicodeToUTF8(const std::wstring &src)
{
        std::string result;
        int n = WideCharToMultiByte(CP_UTF8, 0, src.c_str(), -1, 0, 0, 0, 0);
        result.resize(n);
        ::WideCharToMultiByte(CP_UTF8, 0, src.c_str(), -1, (char*)result.c_str(), (int)result.length(), 0, 0);
        return result;
}

std::wstring gb2312ToUnicode(const std::string& src)
{
        std::wstring result;
        int n = MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, NULL, 0);
        result.resize(n);
        ::MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, (LPWSTR)result.c_str(), (int)result.length());
        return result;
}

std::string gb2312ToUtf8(const std::string& src)
{
        std::wstring strWideChar = gb2312ToUnicode(src);
        return unicodeToUTF8(strWideChar);
}

std::string utf8ToGbk(const std::string& src)
{
        int len = MultiByteToWideChar(CP_UTF8, 0, src.c_str(), -1, NULL, 0);
        wchar_t* wstr = new wchar_t[len + 1];
        memset(wstr, 0, len + 1);
        MultiByteToWideChar(CP_UTF8, 0, src.c_str(), -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;
}

标签:std,编码,转换,src,len,result,str,CP
From: https://www.cnblogs.com/horizonhz/p/17226714.html

相关文章