如何将整数转换为unicode字符?

时间:2019-06-04 12:49:35

标签: c++ unicode

所以我想为我的项目尝试将Unicode转换为整数。我尝试过这样的事情:

 unsigned int foo = (unsigned int)L'آ'; 
 std::cout << foo << std::endl;

如何将其转换回来?换句话说,如何将int转换为相应的Unicode字符?

编辑:我期望输出为整数的unicode值,例如:

cout << (wchar_t) 1570 ; // This should print the unicode value of 1570 (which is :آ)

我正在使用Visual Studio 2013社区及其默认编译器Windows 10 64位Pro

欢呼

2 个答案:

答案 0 :(得分:3)

L'آ'可以很好地用作宽字符,因为它位于0xFFFF之下。但是通常,UTF16包含代理对,因此Unicode代码点不能用单个宽字符表示。您需要使用宽字符串。

您的问题还部分与Windows控制台中的打印UTF16字符有关。如果您使用MessageBoxW查看宽字符串,它将按预期工作:

wchar_t buf[2] = { 0 };
buf[0] = 1570;
MessageBoxW(0, buf, 0, 0);

但是,通常,您需要一个宽字符串来说明代理对,而不是单个宽字符。示例:

int utf32 = 1570;

const int mask = (1 << 10) - 1;
std::wstring str;
if(utf32 < 0xFFFF)
{
    str.push_back((wchar_t)utf32);
}
else
{
    utf32 -= 0x10000;
    int hi = (utf32 >> 10) & mask;
    int lo = utf32 & mask;

    hi += 0xD800;
    lo += 0xDC00;

    str.push_back((wchar_t)hi);
    str.push_back((wchar_t)lo);
}

MessageBox(0, str.c_str(), 0, 0);

请参阅在Windows控制台中打印UTF16的相关文章。

答案 1 :(得分:1)

此处的密钥为setlocale(LC_ALL, "en_US.UTF-8");。 en_US是本地化字符串,您可能需要将其设置为其他值,例如中文zh_CN。

#include <stdio.h>
#include <iostream>

int main() {
    setlocale(LC_ALL, "en_US.UTF-8");
    // This does not work without setlocale(LC_ALL, "en_US.UTF-8");
    for(int ch=30000; ch<30030; ch++) {
        wprintf(L"%lc", ch);
    }
    printf("\n");
    return 0;
}

这里需要注意的是wprintf的使用以及格式化字符串的给出方式:L“%lc”告诉wprintf将字符串和字符视为长字符。

如果要使用此方法来打印一些变量,请使用类型wchat_t

有用的链接: