【问题标题】:How do I convert hex numbers to a character in c++?如何将十六进制数字转换为 C++ 中的字符?
【发布时间】:2017-09-03 03:06:49
【问题描述】:

我正在尝试将十六进制数字转换为 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 作为输入,它会输出字符“[”。我还将如何输出 [?

【问题讨论】:

  • 所以要返回整数值为0x5B的字符?
  • 请记住,大多数系统上的 char 只能保存 2 个十六进制值。
  • 无论您在哪个基数中显示整数,整数都是相同的。您的意思是Base[0] 是值0x5b(即91),而您想要字符'['?如果这就是你的意思,你不需要做任何事情。
  • 数字就是数字。 “十六进制”仅适用于我们如何将数字打印为字符串。你在问:how do I convert an integer into a hex string?或者你在问,how do I convert a hex string back to an integer
  • @JamesGlenn '[' 是 91 是 0x5b。它们都是一样的。

标签: c++ string hex memory-editing


【解决方案1】:

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

【讨论】:

  • 出于某种原因,这给了我 FFFFFFDC,而不是 [.
  • 奇怪。我得到了输出:The character of 0x5B is '[ 和 '['`。我在 Windows 7 上的 Cygwin 上使用 g++ 5.3.0 进行编译。请参阅我的编辑。
  • 我用的是 snprintf 的。
【解决方案2】:

试试这个:

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

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

【讨论】:

  • 没有办法转成字符吗?
  • 您需要该声明中的std::hex 吗? (编译器如何知道以十进制与十六进制打印)?
  • 如果 Base[0] 是 BYTE * 或 unsigned char * 它会打印出来,否则不会。
  • 你想的是printf而不是cout吗?我的理解是cout 没有格式说明符字符串。
  • 我希望它打印字符 [.
猜你喜欢
  • 2018-01-31
  • 2014-03-19
  • 2012-10-16
  • 1970-01-01
  • 2013-02-07
  • 2017-08-23
  • 2011-05-15
  • 2017-08-12
相关资源
最近更新 更多