title: Are there binary memory streams in C++
body: <p>I usually use <code>stringstream</code> to write into in-memory string. Is there a way to write to a char buffer in binary mode? Consider the following code:</p>
  
  <pre><code>stringstream s;
  s &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3;
  const char* ch = s.str().c_str();
  </code></pre>
  
  <p>The memory at <code>ch</code> 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</p>
  
  <pre><code>void f(ostream&amp; os)
  {
      os &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3;
  }
  </code></pre>
  
  <p>And decide outside what kind of stream to use. Something like this:</p>
  
  <pre><code>mycharstream c;
  c &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3; // c.data == 0x313233;
  mybinstream b;
  b &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3; // b.data == 0x010203;
  </code></pre>
  
  <p>Any ideas?</p>