views:

32

answers:

1

I just realized that one can use bitset to output binary data to a stream based on the (fixed) size of the bitset. What's the least-extra-syntax way to output binary data to a stream using integrals?

To show what I mean, here's a program and its output. I'd like the second line of output from this program to be identical to the first line but without resorting to the technique used to output the third line.

int main()
{
  ostringstream bsout, uout, xout;
  bitset<32> bs (0x31323334);
  unsigned u = 0x31323334;

  bsout << bs;
  cout << bsout.str() << endl;

  uout << u;
  cout << uout.str() << endl;

  xout << bitset<32>(u);
  cout << xout.str() << endl;

  return 0;
}


00110001001100100011001100110100
825373492
00110001001100100011001100110100
+2  A: 

Unfortunately, there is no std::bin manipulator akin to oct and hex. Filtering through a bitset object is the preferred method for input and output of binary-formatted numbers.

Kristo
Dang. Thanks, Kristo.I wrote ibitstream, a bit-oriented analogue of istringstream, for predictive parsing of binary data. I was getting ready to write obitstream but wanted to make sure ostringstream didn't already do what I wanted.
plong