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

后端 未结 2 808
佛祖请我去吃肉
佛祖请我去吃肉 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<char>(value);
    cout << "The character of 0x5B is '" << c << "` and '" << static_cast<char>(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 <iostream>
    #include <cstdlib>
    
    int main()
    {
        unsigned int value = 0x5B;
        char c = static_cast<char>(value);
        std::cout << "The character of 0x5B is '" << c << "` and '" << static_cast<char>(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.
    
    0 讨论(0)
  • Try this:

    std::cout << "0x%02hX" << Base[0] << std::endl;
    

    Output should be: 0x5B assuming Base[0] is 0000005B.

    0 讨论(0)
提交回复
热议问题