C++字符转码(GBK和UTF8)

发布时间 2023-06-01 19:05:56作者: 街角_祝福
std::string GB2312ToUtf8(const char* pSrc, int nLen)
{
    string strOut;
    if (pSrc && nLen > 0)
    {
        // ANSI -> UNICODE
        int len = MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)pSrc, nLen, NULL, 0);
        WCHAR* wszUtf8 = new WCHAR[len + 1];
        MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)pSrc, nLen, wszUtf8, len);

        // UNICODE -> UTF-8
        len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);
        char* szUtf8 = new char[len + 1];
        WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL, NULL);

        strOut = szUtf8;
        delete[] szUtf8;
        delete[] wszUtf8;
    }
    return strOut;
}

std::string Utf8ToGB2312(const char* pSrc, int nLen)
{
    string strOut;
    if (pSrc && nLen > 0)
    {
        // UTF8 -> UNICODE
        int len = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pSrc, nLen, NULL, 0);
        unsigned short* wszGBK = new unsigned short[len + 1];
        memset(wszGBK, 0, len * 2 + 2);
        MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pSrc, nLen, (LPWSTR)wszGBK, len);

        // UNICODE -> GBK
        len = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)wszGBK, -1, NULL, 0, NULL, NULL);
        char* szGBK = new char[len + 1];
        memset(szGBK, 0, len + 1);
        WideCharToMultiByte(CP_ACP, 0, (LPWSTR)wszGBK, -1, szGBK, len, NULL, NULL);
        strOut = szGBK;

        delete[]szGBK;
        delete[]wszGBK;
    }
    return strOut;
}