gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:59 26 4
gpt4 key购买 nike

我正在玩弄以下提到的代码: 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com