C#Encoding.Convert与C++ MultiByteToWideChar

Jyo*_*ane 1 c# utf-16 character-encoding

我有一个C++代码片段,它使用MultiByteToWideChar将UTF-8字符串转换为UTF-16

对于C++,如果输入为"HÃ'tel",则输出为"Hôtel",这是正确的

对于C#,如果输入为"HÃ'tel",则输出为"H'tel",这是不正确的.

从UTF8转换为UTF16的C#代码如下所示

Encoding.Unicode.GetString(
            Encoding.Convert(
                Encoding.UTF8,
                Encoding.Unicode,
                Encoding.UTF8.GetBytes(utf8)));
Run Code Online (Sandbox Code Playgroud)

在C++中,转换代码看起来像

MultiByteToWideChar(
    CP_UTF8,            // convert from UTF-8
    0,                  // default flags
    utf8.data(),        // source UTF-8 string
    utf8.length(),      // length (in chars) of source UTF-8 string
    &utf16[0],          // destination buffer
    utf16.length()      // size of destination buffer, in wchar_t's
    )
Run Code Online (Sandbox Code Playgroud)

我希望在C#中获得与C++相同的结果.C#代码有什么问题吗?

Esa*_*ija 6

您似乎希望将字符串字符视为Windows-1252(通常被错误标记为ANSI)代码点,并将这些代码点解码为UTF-8字节,其中Windows-1252 code point == UTF-8 byte value.

接受的答案不起作用的原因是它将字符串字符视为unicode代码点,而不是Windows-1252.它可以逃脱大多数字符,因为Windows 1252将它们映射完全一样unicode的,但类似的字符输入,,,, ,,等.因为Windows 1252比在这个意义上Unicode的映射这些不同会失败.

所以你想要的只是这个:

public static string doWeirdMapping(string arg)
{
    Encoding w1252 = Encoding.GetEncoding(1252);
    return Encoding.UTF8.GetString(w1252.GetBytes(arg));
}
Run Code Online (Sandbox Code Playgroud)

然后:

Console.WriteLine(doWeirdMapping("Hôtel")); //prints Hôtel
Console.WriteLine(doWeirdMapping("HVOLSVÖLLUR")); //prints HVOLSVÖLLUR
Run Code Online (Sandbox Code Playgroud)