Search code examples
c++unicodeutf-16stdstringchar16-t

Convert std::string to utf-16 (like u"some string"); Debugger tells "no suitable conversion exists"


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

I would like to know how to convert a string into unicode for char16_t:

As

int main()
{   
    char16_t c = u'\u0b7f';
    std::cout << (int)c << std::endl;
    return 0;
}

yields decimal 2943 perfectly fine, I now need to know how to inject a 4-digit string into char16_t c = u'\uINSERTHERE'

My stringstream_s contains 4 hex representation letters like '0b82' (decimal: 2946) or '0b77' (decimal: 2935).

I tried

std::string stringstream_s;
....stringstream_s gets assigned....
char16_t c = (u'\u%s',stringstream_s);

and it gives me "no suitable conversion function from std::string to char16_t exists"

So basically speaking, how to convert a string into unicode utf16.....?

I need to know the equivalent of u'\u0b7f' when I just have a bare string of '0b7f'


Solution

  • You need to convert the std::string to an integer first, then you can type-cast the integer to char16_t. In this case, std::stoi() would be the simplest solution:

    std::string s = "0b82";
    char16_t ch = (char16_t) std::stoi(s, nullptr, 16); 
    

    Alternatively, you can use a std::istringstream instead:

    std::string s = "0b82";
    unsigned short i;
    std::istringstream(s) >> std::hex >> i;
    char16_t ch = (char16_t) i;