stringstream and binary data

Student4K picture Student4K · Nov 5, 2017 · Viewed 7.4k times · Source

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

Answer

Galik picture Galik · Nov 5, 2017

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