在c++中转换代码页

Converting Code pages in c++

本文关键字:代码 转换 c++      更新时间:2023-10-16

与c#字符串转换代码(代码页之间)等效的代码是:

public static string Convert(string s)
{
    Encoding encoder = Encoding.GetEncoding(858);
    return Encoding.Default.GetString(encoder.GetBytes(s));
}

在vc++(不是CLR),例如使用WideCharToMultiByte/MultiByteToWideChar WinAPI函数?

是的,MultiByteToWideChar()WideCharToMultiByte()是等效的Win32函数,例如:

std::wstring Convert(const std::wstring &s)
{
    if (s.empty())
        return std::wstring();
    int len = WideCharToMultiByte(858, 0, s.c_str(), s.length(), NULL, 0, NULL, NULL);
    if (len == 0)
        throw std::runtime_error("WideCharToMultiByte() failed"); 
    std::vector<char> bytes(len);
    len = WideCharToMultiByte(858, 0, s.c_str(), s.length(), &bytes[0], len, NULL, NULL);
    if (len == 0)
        throw std::runtime_error("WideCharToMultiByte() failed"); 
    len = MultiByteToWideChar(CP_ACP, 0, &bytes[0], bytes.size(), NULL, 0);
    if (len == 0)
        throw std::runtime_error("MultiByteToWideChar() failed"); 
    std::wstring result;
    result.resize(len);
    len = MultiByteToWideChar(CP_ACP, 0, &bytes[0], bytes.size(), &result[0], len);
    if (len == 0)
        throw std::runtime_error("MultiByteToWideChar() failed"); 
    return result;
}