如何输入4字节的UTF-8字符?

时间:2008-10-15 13:23:52

标签: c++ unicode utf-8 astral-plane

我正在编写一个小应用程序,我需要使用不同字节长度的utf-8字符进行测试。

我可以输入unicode字符进行测试,用utf-8编码,只需做1,2和3个字节,例如:

string in = "pi = \u3a0";

但是如何获得用4字节编码的unicode字符?我试过了:

string in = "aegan check mark = \u10102";

据我所知,应该输出。但是当我打印出来时,我得到了ᴶ0

我错过了什么?

修改

我通过添加前导零来实现它:

string in = "\U00010102";

希望我早点想到这个:)

1 个答案:

答案 0 :(得分:5)

模式\U中有一个较长的转义形式,后跟八位数,而不是\u后跟四位数。这也用于Java和Python,其中包括:

>>> '\xf0\x90\x84\x82'.decode("UTF-8")
u'\U00010102'

但是,如果你正在使用字节字符串,为什么不像上面那样只是转义每个字节,而不是依靠编译器将转换转换为UTF-8字符串?这似乎也更便携 - 如果我编译以下程序:

#include <iostream>
#include <string>

int main()
{
    std::cout << "narrow: " << std::string("\uFF0E").length() <<
        " utf8: " << std::string("\xEF\xBC\x8E").length() <<
        " wide: " << std::wstring(L"\uFF0E").length() << std::endl;

    std::cout << "narrow: " << std::string("\U00010102").length() <<
        " utf8: " << std::string("\xF0\x90\x84\x82").length() <<
        " wide: " << std::wstring(L"\U00010102").length() << std::endl;
}

在win32上使用我当前的选项cl给出:

warning C4566: character represented by universal-character-name '\UD800DD02' cannot be represented in the current code page (932)

编译器尝试将字节字符串中的所有unicode转义转换为系统代码页,与UTF-8不同,它不能代表所有unicode字符。奇怪的是,它已经理解\U00010102在UTF-16(其内部unicode表示)中是\uD800\uDD02并且在错误消息中损坏了转义......

运行时,程序会打印:

narrow: 2 utf8: 3 wide: 1
narrow: 2 utf8: 4 wide: 2

请注意,UTF-8字节串和宽字符串是正确的,但编译器无法转换"\U00010102",给出字节字符串"??",结果不正确。