I usually use stringstream
to write into in-memory string. Is there a way to write to a char buffer in binary mode? Consider the following code:
stringstream s;
s << 1 << 2 << 3;
const char* ch = s.str().c_str();
The memory at ch
will look like this: 0x313233 - the ASCII codes of the characters 1, 2 and 3. I'm looking for a way to write the binary values themselves. That is, I want 0x010203 in the memory. The problem is that I want to be able to write a function
void f(ostream& os)
{
os << 1 << 2 << 3;
}
And decide outside what kind of stream to use. Something like this:
mycharstream c;
c << 1 << 2 << 3; // c.data == 0x313233;
mybinstream b;
b << 1 << 2 << 3; // b.data == 0x010203;
Any ideas?
To read and write binary data to streams, including stringstreams, use the read() and write() member functions. So
unsigned char a(1), b(2), c(3), d(4);
std::stringstream s;
s.write(reinterpret_cast<const char*>(&a), sizeof(unsigned char));
s.write(reinterpret_cast<const char*>(&b), sizeof(unsigned char));
s.write(reinterpret_cast<const char*>(&c), sizeof(unsigned char));
s.write(reinterpret_cast<const char*>(&d), sizeof(unsigned char));
s.read(reinterpret_cast<char*>(&v), sizeof(unsigned int));
std::cout << std::hex << v << "\n";
This gives 0x4030201
on my system.
Edit: To make this work transparently with the insertion and extraction operators (<< and >>), your best bet it to create a derived streambuf that does the right thing, and pass that to whatever streams you want to use.