1

I have a method deserialize taking a reference to opened std::istream where normally I pass in an std::ifstream opened with std::ios::binary option.

Now I would like to test it with some binary (hex) literals but I do not know how to feed that data into the std::istream.

I tried something similar like in this 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);
}

Which fails because that data is not read/fed as binary.

How can I do it?

Community
  • 1
  • 1
Patryk
  • 18,244
  • 37
  • 110
  • 212

1 Answers1

2

You don't have any binary data in your buffer, but characters. You have a plain c-style character literal.

To feed your input from binary data you need a declaration like this:

unsigned char buffer[] = { 0x0a, 0x0b, 0x0c, 0x0d, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 
                            0x00, 0x00, 0x00, 0x42, 0x04, 0x10, 0x00, 0x00 };
πάντα ῥεῖ
  • 83,259
  • 13
  • 96
  • 175