如何在 c++ 中将十六进制数字转换为字符
How do I convert hex numbers to a character in c++?
我正在尝试将十六进制数转换为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。
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 如何在C++中将十六进制字符串转换为文本数据
- 使用 sprintf 将十六进制0xAABBCC转换为字符串"AA:BB:CC"
- C++十六进制字符串转换为十六进制的字符 *
- 如何在C++中将十六进制字符串转换为字节字符串?
- 从十六进制字符串转换为十六进制字符数组
- 以C++格式将十六进制字符串转换为十进制数
- 将大十六进制数转换为十进制形式(以 10 为基数的形式)的算法
- 如何将十六进制字符串转换为 HTML 实体
- 如何在C++中将十六进制字符转换为二进制
- 在 c++ 中使用字符串流将 4 个字符的十六进制字符串转换为有符号的短字符串
- 从char阵列中提取十六进制数字
- 将 std::十六进制字符串转换为 std::array<T, 6>
- 如何在 c++ 中将十六进制数字转换为字符
- 如何在 c++ 中将十六进制字符串转换为长整型字符串
- 使用字符串格式限制十六进制数字的数量
- 将十六进制数字从无符号字符转换为字符串
- 将十六进制数的 char[] 转换为对应于 ASCII 表中十六进制数字的字母的 char[] 并反转
- 将std::字符串数字转换为十六进制数字
- 将字节转换为两位十六进制数字