【问题标题】:How to feed binary hex literal into std::istream?如何将二进制十六进制文字输入 std::istream?
【发布时间】:2016-05-04 16:44:41
【问题描述】:

我有一个方法deserialize 引用打开的std::istream,通常我会传入一个std::ifstreamstd::ios::binary 选项打开。

现在我想用一些二进制(十六进制)文字对其进行测试,但我不知道如何将该数据输入std::istream

我在 answer 中尝试过类似的东西

struct membuf : std::streambuf
{
  membuf(char* begin, char* end)
  {
    this->setg(begin, begin, end);
  }
};

int main()
{
  char buffer[] = "0a0b0c0d000000480000000000420410000";

  membuf sbuf(buffer, buffer + sizeof(buffer) - 1);
  std::istream in(&sbuf);

  deserialize(in);
}

失败是因为该数据不是以二进制形式读取/提供的。

我该怎么做?

【问题讨论】:

  • 你忘记std::istringstream了吗?
  • @LogicStuff 你能在这里解释一下如何使用它吗?
  • 我误解了一点。你刚刚得到了答案。
  • @LogicStuff 这就是我的想法;d 我不认为我可以在这里使用istringstream

标签: c++ binary hex istream


【解决方案1】:

您的buffer 中没有任何二进制数据,而是字符。你有一个纯 c 风格的字符文字。

要从二进制数据中获取输入,您需要这样的声明:

unsigned char buffer[] = { 0x0a, 0x0b, 0x0c, 0x0d, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 
                            0x00, 0x00, 0x00, 0x42, 0x04, 0x10, 0x00, 0x00 };

【讨论】:

  • 这对struct membufstd::streambuf 的东西起到了作用
  • 很抱歉,您如何将此缓冲区转换为 istream 数据类型?就是这个问题,我也被这个问题困住了。
猜你喜欢
  • 1970-01-01
  • 2021-10-27
  • 2014-10-30
  • 2012-04-08
  • 2011-12-22
  • 1970-01-01
  • 2012-06-26
  • 2012-03-28
  • 2014-03-11
相关资源
最近更新 更多