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

2019-03-04 19:48发布

问题:

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_tostring(int state, int index, int size) {
    int stringAddress = lua_tolstring(state, index, 0);
    const char* const Base = (const char* const)stringAddress;
    return Base[0];
};

Base[0] would return a hex number like: 0000005B

If you go here http://string-functions.com/hex-string.aspx and put 0000005B as the input it outputs the character "[". How would I also output [?

回答1:

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.


回答2:

Try this:

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

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