假设我有
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/