tags:

views:

455

answers:

2

Hello,

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?

+1  A: 

Well, just use characters, not integers.

s << char(1) << char(2) << char(3);
Lukáš Lalinský
+5  A: 

To read and write binary data to streams, including stringstreams, use the read() and write() member functions. So

int a(1), b(2), c(3);
stringstream s;
s.write(&a, sizeof(int));
s.write(&b, sizeof(int));
s.write(&c, sizeof(int));

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.

KeithB
It definitely answers the first part of the question, but is there a way to make the insertion look always the same (i.e. s << a) but the inner data representation differ depending on the type of the stream?
FireAphis
An article that explains how to derive streambuf: http://spec.winprog.org/streams/
FireAphis
Your own streambuf can't do this; formatting is done in the (non-virtual) istream and ostream methods and the result of that is what the streambuf sees.
Roger Pate