c++ - 作为 UTF-8 值的无符号整数

标签 c++ c++11 unicode utf-8

假设我有

uint32_t a(3084);

我想创建一个存储 unicode 字符 U+3084 的字符串,这意味着我应该获取 a 的值并将其用作UTF8 表/字符集中的右字符。

现在,显然 std::to_string() 对我不起作用,标准中有很多函数可以在数值和 char 之间进行转换,我找不到任何东西授予我 UTF8 支持并输出 std::string

我想问一下我是否必须从头开始创建这个函数,或者 C++11 标准中有什么可以帮助我的;请注意,我的编译器 (gcc/g++ 4.8.1) 不提供对 codecvt 的完整支持。

最佳答案

这是一些不难转换为 C 的 C++ 代码。改编自 older answer .

std::string UnicodeToUTF8(unsigned int codepoint)
{
    std::string out;

    if (codepoint <= 0x7f)
        out.append(1, static_cast<char>(codepoint));
    else if (codepoint <= 0x7ff)
    {
        out.append(1, static_cast<char>(0xc0 | ((codepoint >> 6) & 0x1f)));
        out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));
    }
    else if (codepoint <= 0xffff)
    {
        out.append(1, static_cast<char>(0xe0 | ((codepoint >> 12) & 0x0f)));
        out.append(1, static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));
        out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));
    }
    else
    {
        out.append(1, static_cast<char>(0xf0 | ((codepoint >> 18) & 0x07)));
        out.append(1, static_cast<char>(0x80 | ((codepoint >> 12) & 0x3f)));
        out.append(1, static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));
        out.append(1, static_cast<char>(0x80 | (codepoint & 0x3f)));
    }
    return out;
}

关于c++ - 作为 UTF-8 值的无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19968705/

相关文章:

c++ - 公共(public) : static constant string declaraion/initialization issue

c++ - 给定 c 中的一个固定数,找到所有可能的加法和组合(给定一个和,找到它可能的加法和排列。)

c++ - Lambda 变量捕获

php - 如何使用 php 将文本转换为 unicode 代码点,如\u0054\u0068\u0069\u0073?

c++ - Apple C++ LLVM 编译器 4.x 和 UNICODE : when needed? UNICODE 是默认编译器字符集吗?使您的代码同时编译 ANSI 和 UNICODE 版本

对象的 C++ vector 和对析构函数的过度调用?

c++ - Netbeans 讨厌 nullptr 但仍然工作正常

javascript - -nan 在 C++ 中是什么意思?为什么 pow(-4, -2.1) 返回 -nan?

c++ - 基础构造函数和派生构造函数之间的歧义

python - 在 Python 中生成随机 UTF-8 字符串