【问题标题】:Char to represent hex number from int with prefix '0x0'Char 表示来自 int 的十六进制数,前缀为 '0x0'
【发布时间】:2020-08-24 06:24:28
【问题描述】:

我的目标:我正在使用 Visual Studio 2015 中的 MFC 构建一个应用程序。我创建了一个包含两列的表,其中包含许多寄存器的数字和值,如下所示:

为了方便地填写此表,我想创建一个 for 循环,它将 LPCSTR 字符串(自动解释为 const char)发送到名为 InsertItem 的 CListCtrl 类的成员函数。我希望这个 LPCSTR 字符串看起来像一个十六进制数 0x01 或 0x14,而前缀 0x 之后的值将由十六进制基数的循环索引确定。例如:


char buffer[3*sizeof(int)];
int l_iItem;
for (int index = REGS_NUMBER; index >= 0; index--) {
        // Somehow make buffer look like 0xN when N is the index value in hex representation stuffed with 
        // zeroes if needed;
        l_iItem = m_EditableList.InsertItem(LVIF_TEXT | LVIF_STATE, 0, buffer, 0, LVIS_SELECTED, 0, 0);
        m_EditableList.SetItemText(l_iItem, 1, "00000000");

我看到了很多关于这个主题的问题,但几乎所有人都提出了解决这个问题的方法(正如在 cmets 上所说的那样)。如果有人可以向我推荐适当的功能,我将不胜感激。

谢谢。

================================================ ==============================

按照 Tushar 的建议,我尝试添加这些标题:

#include <iostream>
#include <sstream>
#include <iomanip>

并尝试运行以下代码:

    char* n;
    
    int i = 7;
    //std::istringstream s("2A");


    n << std::hex << std::showbase << i;

    std::cout << n;

我得到的错误:

expression must have integral or unscoped enum.
'hex' is not a member of std.
'showbase' is not a member of std.
undeclared identifier.
undeclared identifier.

另一个试验:正如 cmets 所建议的那样,我尝试使用 ostringstream 而不是 char*,如下所示:

    std::ostringstream ss;
    int i = 7;
    ss << std::hex << std::showbase << i;

    std::string str = ss.str();
    const char *output = str.c_str();

我得到了同样的错误,尽管我包含了所有必要的标题。可能是什么问题?

【问题讨论】:

  • 创建一个char 数组并使用fprintf 将数字写入其中。
  • 打印你想要做的,但你想“打印”到一个字符串而不是控制台。阅读std::ostringstream
  • &lt;&lt; std::hex 不适用于 char*。它是标准库的 IOStreams 部分的一部分。它将适用于std::coutstd::ofstreamstd::ostringstream 等。

标签: c++ formatting hex


【解决方案1】:

ios_base& 十六进制 (ios_base& str);

用于将 str 流的基域格式标志设置为十六进制。当 basefield 设置为十六进制时,插入流中的整数值以十六进制表示(即基数 16)。对于输入流,在设置此标志时,提取的值也应以十六进制表示。

如果要解析十六进制字符串

std::istringstream("2A") >> std::hex >> n;

使用十六进制的示例。

#include <iostream>
#include <sstream>
#include <iomanip>
int main()
{
    std::cout << "Parsing string \"10 0x10 010\"\n";
 
    int n1, n2, n3;
    std::istringstream s("10 0x10 010");
    s >> std::setbase(16) >> n1 >> n2 >> n3;
    std::cout << "hexadecimal parse: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
     s >> std::setbase(0) >> n1 >> n2 >> n3;
    std::cout << "prefix-dependent parse: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
 
    std::cout << "hex output: " << std::setbase(16)
              << std::showbase << n1 << ' ' << n2 << ' ' << n3 << '\n';
}

【讨论】:

  • 感谢您的评论,但我无法让它工作。你能给我举个例子吗?此外,它并不能完全解决我的问题,因为我希望它也有一个前缀“0x0”或只是“0x”,具体取决于整数的长度(即 0x01 或 0x15)
  • 我不明白你到底在做什么。如果您显示更多代码会更有意义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-27
  • 2012-05-09
  • 1970-01-01
  • 1970-01-01
  • 2011-02-09
  • 2015-11-07
  • 2014-12-20
相关资源
最近更新 更多