To read and write binary data to streams, including string streams, use the read () and write () functions. So
unsigned char a(1), b(2), c(3), d(4); std::stringstream s; s.write(reinterpret_cast<const char*>(&a), sizeof(unsigned char)); s.write(reinterpret_cast<const char*>(&b), sizeof(unsigned char)); s.write(reinterpret_cast<const char*>(&c), sizeof(unsigned char)); s.write(reinterpret_cast<const char*>(&d), sizeof(unsigned char)); s.read(reinterpret_cast<char*>(&v), sizeof(unsigned int)); std::cout << std::hex << v << "\n";
This gives 0x4030201 on my system.
Edit: To make this work transparently with insert and extract operators (<<and →), it is best to create a streambuf derivative for it that does the right thing, and pass that to the threads you want to use.
KeithB Oct 13 '09 at 11:14 2009-10-13 11:14
source share