如何在 c++ 中将十六进制数字转换为字符

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

本文关键字:十六进制数字 转换 字符 c++      更新时间:2023-10-16

我正在尝试将十六进制数转换为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 作为输入,它将输出字符"["。我怎么也会输出 [?

要将数字打印为字符,可以将其分配给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),
         "%cn", 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.

试试这个:

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

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