编码转换

#include <Windows.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;
	int n = MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, NULL, 0);
	strWideChar.resize(n);
	::MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, (LPWSTR)strWideChar.c_str(), (int)strWideChar.length());

	std::string result;
	int i = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, 0, 0, 0, 0);
	result.resize(i);
	::WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, (char*)result.c_str(), (int)result.length(), 0, 0);

	return result;
}

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;
}
posted @ 2023-03-17 14:31  YiXiaoKezz  阅读(23)  评论(0编辑  收藏  举报