0

I am using std::bitset to give me a binary representation of a number. I now want to use this and output to std::cout using only the binary representation - I do not want the ASCII representation of std::bitset - I merely want to output my bitset as it is in memory.

bitset<32> bits = a;
cout << bits; //produces the ASCII characters for '1' and '0' depending on a
Zambezi
  • 767
  • 1
  • 9
  • 19
  • what is you expected output? – Bryan Chen Sep 30 '14 at 01:49
  • My expected output would be garbage when you look at it's ascii representation - but if you were to look at its binary representation, it would be something like 10101011101010111010101110101011 – Zambezi Sep 30 '14 at 01:51
  • so you want get raw data out of it? only way is `to_ulong` and `to_ullong`, which won't work for large bitset – Bryan Chen Sep 30 '14 at 01:54
  • bits is giving back numeric 0,1, i tried it and test this. this prints -48, -47 , if it was ascii 0 and 1, i would have got 0,1 for (int i = 0; i < bits.size(); ++i) { cout << (bits[i]-'0') ; } – radar Sep 30 '14 at 02:08
  • Honestly, `bitset` is a bit junk. Find another solution. – Yakk - Adam Nevraumont Sep 30 '14 at 02:16
  • Maybe I'm misunderstanding your intent but did you try [std::bitset::to_string](http://en.cppreference.com/w/cpp/utility/bitset/to_string)? It returns a string of the binary representation. – jpw Sep 30 '14 at 02:41

1 Answers1

0

If your bitset is within the limits of the function to_ulong or to_ullong, you can use those functions and output those to a binary file directly.

If your bitset exceeds the amount that an unsigned long or unsigned long long can store, the function will throw an overflow exception. This means that you need to extract subsets of the bitset, and for each subset store the unsigned long or unsigned long long to file.

Unfortunately std::bitset does not provide a direct subset function, so you would have to write that yourself.

DoubleYou
  • 1,057
  • 11
  • 25