How do I convert hex numbers to a character in c++?

后端 未结 2 809
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 03:30

I\'m trying to convert a hex number to a character in C++. I looked it up but I can\'t find an answer that works for me.

Here is my code:

char mod_tostr         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-26 04:13

    To print a number as a character, you can either assign it to a char variable or cast it to a char type:

    unsigned int value = 0x5B;
    char c = static_cast(value);
    cout << "The character of 0x5B is '" << c << "` and '" << static_cast(value) << "'\n";
    

    You could also use snprintf:

    char text_buffer[128];
    unsigned int value = 0x5B;
    snprintf(&text_buffer[0], sizeof(text_buffer),
             "%c\n", value);
    puts(text_buffer);
    

    Example program:

    #include 
    #include 
    
    int main()
    {
        unsigned int value = 0x5B;
        char c = static_cast(value);
        std::cout << "The character of 0x5B is '" << c << "` and '" << static_cast(value) << "'\n";
    
        std::cout << "\n"
                  << "Paused.  Press Enter to continue.\n";
        std::cin.ignore(1000000, '\n');
        return EXIT_SUCCESS;
    }
    

    Output:

    $ ./main.exe
    The character of 0x5B is '[` and '['
    
    Paused.  Press Enter to continue.
    

提交回复
热议问题