c++ - "Ü"的 UTF 编码返回 3 个字节而不是 "real"unicode

标签 c++ unicode encoding utf-8

我正在玩弄以下提到的代码: https://stackoverflow.com/a/21575607/2416394因为我在使用 TinyXML 编写正确的 utf8 xml 时遇到问题。

好吧,我需要对“带有分音符的拉丁文大写字母 U”进行编码,即 Ü 以正确写入 XML 等。

这是从上面的帖子中获取的代码:

std::string codepage_str = "Ü";
int size = MultiByteToWideChar( CP_ACP, MB_COMPOSITE, codepage_str.c_str(),
                                codepage_str.length(), nullptr, 0 );
std::wstring utf16_str( size, '\0' );
MultiByteToWideChar( CP_ACP, MB_COMPOSITE, codepage_str.c_str(),
                     codepage_str.length(), &utf16_str[ 0 ], size );

int utf8_size = WideCharToMultiByte( CP_UTF8, 0, utf16_str.c_str(),
                                     utf16_str.length(), nullptr, 0,
                                     nullptr, nullptr );
std::string utf8_str( utf8_size, '\0' );
WideCharToMultiByte( CP_UTF8, 0, utf16_str.c_str(),
                     utf16_str.length(), &utf8_str[ 0 ], utf8_size,
                     nullptr, nullptr );

结果是一个 std::string,大小为 3,字节如下:

-       utf8_str    "Ü"   std::basic_string<char,std::char_traits<char>,std::allocator<char> >
        [size]  0x0000000000000003  unsigned __int64
        [capacity]  0x000000000000000f  unsigned __int64
        [0] 0x55 'U'    char
        [1] 0xcc 'Ì'    char
        [2] 0x88 'ˆ'    char

当我将其写入 utf8 文件时。十六进制值保留在那里:0x55 0xCC 0x88,Notepad++ 向我显示正确的字符 Ü

然而,当我通过 Notepad++ 将另一个 Ü 添加到文件并再次保存时,新写入的 Ü 显示为 0xC3 0x9C (这是我一开始就预料到的)。

我不明白,为什么我得到这个字符的 3 字节表示而不是预期的 unicode 代码点 U+00DC。

尽管 Notepad++ 正确显示它,但我们的专有系统将 0xC3 0x 9C 呈现为 Ü 并通过呈现 0x55 0xCC 0x88 处中断UÌ^ 无法将其识别为两字节 utf 8

最佳答案

Unicode 很复杂。至少有两种不同的方法可以获取 Ü:

  1. 带分音符的拉丁文大写字母 U 是 Unicode 代码点 U+00DC

  2. LATIN CAPITAL LETTER U 是 Unicode codepoint U+0055COMBINING DIAERESIS 是 Unicode codepoint U+0308 .

U+00DCU+0055 U+0308 都显示为 Ü

在UTF-8中,Unicode码位U+00DC被编码为0xC3 0x9CU+0055被编码为0x55 U+0308被编码为0xCC 0x88

您的专有系统似乎有错误。

编辑:根据 MultiByteToWideChar() documentation 获得您期望的结果,使用 MB_PRECOMPOSED 而不是 MB_COMPOSITE

关于c++ - "Ü"的 UTF 编码返回 3 个字节而不是 "real"unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39588795/

相关文章:

c++ - 指向成员对象的指针 - 中断线程

c++ - 为什么要使用引用来获取 *char?当我们使用指针时不使用引用不是更好吗?

mysql - 如何在phpMyAdmin中显示UTF-8字符?

python - 如何检测Python中未解码的字符?

java - 在 Java 中检测(或最佳猜测)传入的字符串编码

c++ - 如何读取 EXE 字节,存储到 char 数组,然后将字节写入新的 EXE 文件?

c++ - 类内部的成员变量分配在哪里?

c++ - C++中阿拉伯字符串的反转

Python 2.7 - xlrd - 将字符串与单元格值匹配

networking - 在有损网络上流式传输视频