10

What is needed (some method overrides?) in order to read/write binary data to/from std::basic_stringstream? I am trying the following code, but it does not work as I supposed:

std::basic_stringstream<uint64_t> s;
uint64_t a = 9;
s << a;
uint64_t b;
s >> b;
std::cout << b << std::endl;

but I get "0" printed (built with GCC).

Student4K
  • 916
  • 2
  • 9
  • 20
  • There is no built-in specialization of `std::char_traits`. You won't be able to instantiate `std::basic_stringstream` until you provide one. Now, what is it you are trying to achieve? Your code doesn't make much sense to me. [It prints `9`](http://rextester.com/BDPZD89619) if you just use plain vanilla `std::stringstream`, but there's no "binary data" in there, and it's not clear what you mean by that. – Igor Tandetnik Nov 05 '17 at 19:02
  • no offense, but afaik `basic_stringstream` is for those that know what they are doing. What do you actually want to achieve? I am almost sure that `basic_stringstream` isnt the right tool for it – 463035818_is_not_an_ai Nov 05 '17 at 19:05
  • Are you trying to convert a 64-bit decimal number to a textual binary representation, such as "1001" for 9? – Thomas Matthews Nov 05 '17 at 19:08

1 Answers1

15

If you want to read/write binary data you can't use << or >> you need to use the std::stringstream::read and std::stringstream::write functions.

Also you need to use the <char> specialization because only char can safely alias other types.

So you could do it this way:

std::stringstream ss;

std::uint64_t n1 = 1234567890;

ss.write((char const*) &n1, sizeof(n1)); // sizeof(n1) gives the number of char needed

std::uint64_t n2;

ss.read((char*) &n2, sizeof(n2));

std::cout << n2 << '\n';

Output:

1234567890
Galik
  • 47,303
  • 4
  • 80
  • 117
  • why can't you use `<<` `>>` with binary stream? – Tellegar Apr 19 '23 at 19:37
  • @Tellegar Both `<<` and `>>` are *formatting* operations - that modify/change the data being read or written. Binary streams need to be transmitted and received unchanged. – Galik Apr 19 '23 at 19:56