Unsigned integer as UTF-8 value

后端 未结 4 1216
故里飘歌
故里飘歌 2021-02-03 16:46

assuming that I have

uint32_t a(3084);

I would like to create a string that stores the unicode character U+3084 which means that I

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-03 16:55

    std::string_convert::to_bytes has a single-char overload just for you.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    // utility function for output
    void hex_print(const std::string& s)
    {
        std::cout << std::hex << std::setfill('0');
        for(unsigned char c : s)
            std::cout << std::setw(2) << static_cast(c) << ' ';
        std::cout << std::dec << '\n';
    }
    
    int main()
    {
        uint32_t a(3084);
    
        std::wstring_convert, char32_t> conv1;
        std::string u8str = conv1.to_bytes(a);
        std::cout << "UTF-8 conversion produced " << u8str.size() << " bytes:\n";
        hex_print(u8str);
    }
    

    I get (with libc++)

    $ ./test
    UTF-8 conversion produced 3 bytes:
    e0 b0 8c 
    

提交回复
热议问题