12

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).

3
  • There is no built-in specialization of std::char_traits<uint64_t>. You won't be able to instantiate std::basic_stringstream<uint64_t> 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 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. Commented Nov 5, 2017 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 Commented Nov 5, 2017 at 19:05
  • Are you trying to convert a 64-bit decimal number to a textual binary representation, such as "1001" for 9? Commented Nov 5, 2017 at 19:08

1 Answer 1

18

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
Sign up to request clarification or add additional context in comments.

2 Comments

why can't you use << >> with binary stream?
@Tellegar Both << and >> are formatting operations - that modify/change the data being read or written. Binary streams need to be transmitted and received unchanged.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.