gpt4 book ai didi

c++ - 如何使用 std 库在 Linux 上从 utf-16 转换为 utf-32?

转载 作者:太空狗 更新时间:2023-10-29 23:51:06 28 4
gpt4 key购买 nike

在 MSVC 上,将 utf-16 转换为 utf-32 很容易 - 使用 C11 的 codecvt_utf16 locale facet。但是在 GCC (gcc (Debian 4.7.2-5) 4.7.2) 中,这个新功能似乎还没有实现。有没有办法在没有 iconv 的 Linux 上执行这种转换(最好使用 std 库的转换工具)?

最佳答案

将 UTF-16 解码为 UTF-32 非常容易。

您可能希望在编译时检测您正在使用的 libc 版本,并在检测到损坏的 libc(没有您需要的功能)时部署您的转换例程。

输入:

  • 指向源 UTF-16 数据的指针(char16_t *ushort *,-- 为了方便 UTF16 *);<
  • 它的大小;
  • 指向 UTF-32 数据的指针(char32_t *uint * -- 为了方便 UTF32 *)。

代码如下:

void convert_utf16_to_utf32(const UTF16 *input, 
size_t input_size,
UTF32 *output)
{
const UTF16 * const end = input + input_size;
while (input < end) {
const UTF16 uc = *input++;
if (!is_surrogate(uc)) {
*output++ = uc;
} else {
if (is_high_surrogate(uc) && input < end && is_low_surrogate(*input))
*output++ = surrogate_to_utf32(uc, *input++);
else
// ERROR
}
}
}

留下了错误处理。您可能想要将 U+FFFD¹ 插入到流中并继续,或者只是退出,这完全取决于您。辅助功能很简单:

int is_surrogate(UTF16 uc) { return (uc - 0xd800u) < 2048u; }
int is_high_surrogate(UTF16 uc) { return (uc & 0xfffffc00) == 0xd800; }
int is_low_surrogate(UTF16 uc) { return (uc & 0xfffffc00) == 0xdc00; }

UTF32 surrogate_to_utf32(UTF16 high, UTF16 low) {
return (high << 10) + low - 0x35fdc00;
}

¹ 比照。统一码:

² 还要考虑 !is_surrogate(uc) 分支是迄今为止最常见的分支(以及第二个 if 中的非错误路径),您可能希望使用 __builtin_expect 或类似的。

关于c++ - 如何使用 std 库在 Linux 上从 utf-16 转换为 utf-32?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23919515/

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