Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output integral to ostringstream as binary?

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
like image 722
plong Avatar asked Mar 27 '26 22:03

plong


1 Answers

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.

like image 89
Michael Kristofik Avatar answered Mar 29 '26 13:03

Michael Kristofik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!