0

我正在尝试将十六进制数字转换为 C++ 中的字符。我查了一下,但找不到适合我的答案。

这是我的代码:

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] 将返回一个十六进制数,如:0000005B

如果你去这里http://string-functions.com/hex-string.aspx并将 0000005B 作为输入,它会输出字符“[”。我还将如何输出 [?

4

2 回答 2

0

要将数字打印为字符,您可以将其分配给char变量或将其强制转换为char类型:

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

你也可以使用snprintf

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

示例程序:

#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;
}

输出:

$ ./main.exe
The character of 0x5B is '[` and '['

Paused.  Press Enter to continue.
于 2017-04-07T17:05:10.560 回答
-2

尝试这个:

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

输出应该是:0x5B 假设 Base[0] 是 0000005B。

于 2017-04-07T16:57:16.387 回答