将 unicode 代码点转换为 utf-16
Convert unicode codepoint to utf-16
在 Windows 上的 C++ 中,如何将 &#xhhhh;
形式的 xml 字符引用转换为 utf-16 小端字符串?
我在想,如果 hhhh 部分不超过 4 个字符,那么它就是 2 个字节,适合一个 utf-16 字符。但是,这个 wiki page has a table of character references 和靠近底部的一些是 5 位十六进制数字,两个字节都放不下。如何将它们转换为 utf-16?
我想知道 MultiByteToWideChar 函数是否能够完成这项工作。
我对大于 2 个字节的代码点如何转换为 utf-16 的理解不足! (或者就此而言,我不太确定大于 1 字节的代码点如何转换为 utf-8,但这是另一个问题)。
谢谢。
Unicode 代码点 (UTF-32) 有 4 个字节宽,可以使用以下代码(我碰巧有)将其转换为 UTF-16
字符(和可能的代理项)。
它没有经过严格测试,因此非常感谢接受错误报告:
/**
* Converts U-32 code point to UTF-16 (and optional surrogate)
* @param utf32 - UTF-32 code point
* @param utf16 - returned UTF-16 character
* @return - The number code units in the UTF-16 char (1 or 2).
*/
unsigned utf32_to_utf16(char32_t utf32, std::array<char16_t, 2>& utf16)
{
if(utf32 < 0xD800 || (utf32 > 0xDFFF && utf32 < 0x10000))
{
utf16[0] = char16_t(utf32);
utf16[1] = 0;
return 1;
}
utf32 -= 0x010000;
utf16[0] = char16_t(((0b1111'1111'1100'0000'0000 & utf32) >> 10) + 0xD800);
utf16[1] = char16_t(((0b0000'0000'0011'1111'1111 & utf32) >> 00) + 0xDC00);
return 2;
}
在 Windows 上的 C++ 中,如何将 &#xhhhh;
形式的 xml 字符引用转换为 utf-16 小端字符串?
我在想,如果 hhhh 部分不超过 4 个字符,那么它就是 2 个字节,适合一个 utf-16 字符。但是,这个 wiki page has a table of character references 和靠近底部的一些是 5 位十六进制数字,两个字节都放不下。如何将它们转换为 utf-16?
我想知道 MultiByteToWideChar 函数是否能够完成这项工作。
我对大于 2 个字节的代码点如何转换为 utf-16 的理解不足! (或者就此而言,我不太确定大于 1 字节的代码点如何转换为 utf-8,但这是另一个问题)。
谢谢。
Unicode 代码点 (UTF-32) 有 4 个字节宽,可以使用以下代码(我碰巧有)将其转换为 UTF-16
字符(和可能的代理项)。
它没有经过严格测试,因此非常感谢接受错误报告:
/**
* Converts U-32 code point to UTF-16 (and optional surrogate)
* @param utf32 - UTF-32 code point
* @param utf16 - returned UTF-16 character
* @return - The number code units in the UTF-16 char (1 or 2).
*/
unsigned utf32_to_utf16(char32_t utf32, std::array<char16_t, 2>& utf16)
{
if(utf32 < 0xD800 || (utf32 > 0xDFFF && utf32 < 0x10000))
{
utf16[0] = char16_t(utf32);
utf16[1] = 0;
return 1;
}
utf32 -= 0x010000;
utf16[0] = char16_t(((0b1111'1111'1100'0000'0000 & utf32) >> 10) + 0xD800);
utf16[1] = char16_t(((0b0000'0000'0011'1111'1111 & utf32) >> 00) + 0xDC00);
return 2;
}