【问题标题】:Converting Code pages in c++在 C++ 中转换代码页
【发布时间】:2014-08-12 22:01:31
【问题描述】:

什么相当于C#字符串转换代码(代码页之间):

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

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

【问题讨论】:

  • 您已经知道需要调用的函数,并且可以轻松查找它们的文档,那么问题是什么?

标签: c++ winapi codepages


【解决方案1】:

是的,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;
}

【讨论】:

  • @MooingDuck:C# 代码未从代码页 858 转换为 UTF-16。 Encoding.Default 代表系统默认代码页 (CP_ACP),而不是代码页 858。对 Encoding.Default.GetString() 的调用正在解释代码页 858 字节,就好像它们在系统代码页中编码一样。所以 C# 代码和我的代码在做同样的事情,这就是为什么我按照我的方式编写它。
  • @MooingDuck:只有当 C# 代码使用 encoder.GetString() 而不是 Encoding.Default.GetString() 时,您所说的才是正确的。
猜你喜欢
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多