C++: Convert hex representation of UTF16 char into decimal (like python's int(hex_data, 16))

房东的猫 提交于 2019-12-23 05:50:24

问题


I found an explanation to decode hex-representations into decimal but only by using Qt: How to get decimal value of a unicode character in c++

As I am not using Qt and cout << (int)c does not work (Edit: it actually does work if you use it properly..!):

How to do the following:

I got the hex representation of two chars which were transmitted over some socket (Just figured out how to get the hex repr finally!..) and both combined yield following utf16-representation:

char c = u"\0b7f"

This shall be converted into it's utf16 decimal value of 2943! (see it at utf-table http://www.fileformat.info/info/unicode/char/0b7f/index.htm)

This should be absolut elementary stuff, but as a designated Python developer compelled to use C++ for a project I am hanging this issue for hours....


回答1:


Use a wider character type (char is only 8 bits, you need at least 16), and also the correct format for UTC literals. This works (live demo):

#include <iostream>

int main()
{
    char16_t c = u'\u0b7f';

    std::cout << (int)c << std::endl;  //output is 2943 as expected

    return 0;
}


来源:https://stackoverflow.com/questions/40546800/c-convert-hex-representation-of-utf16-char-into-decimal-like-pythons-inthe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!