Click to See Complete Forum and Search --> : Loading std::string with binary data


dirk102
February 16th, 2008, 09:26 PM
Hi.
I'm writing a little communication server and I would like to simplify the building of 'packets'. A packet could send a message, or tell the server to return info on something. I would like to use std::string to store the appropriate data for the packet as my socket wrapper uses it.

How I would like to build the packet is like so:

-code-
int cat=10;
float chicken=1.26;
long monkey=123134;

std::string packet;

packet << cat << chicken << monkey;
-code-

I have looked at std::string stream but it converts anything i throw at it into an ascii representation as so:
packet == "101.26123134"


Is there a ready made solution in the STL for this?
I am trying to avoid using boost.
Or would just constructing my own class for handling this be easiest?

Thank you.

Marc G
February 17th, 2008, 04:15 AM
For storing binary data you could use std::vector.

Lindley
February 17th, 2008, 11:20 AM
Since you're intentionally throwing away type safety anyway, just memcpy to a char array. As a char array can be effortlessly converted to a std::string (and back using c_str()), this won't introduce any need to make changes to the portion that relies on std::string.

You may need to control the size of the array dynamically, so make sure you know how to do that.

Also, be careful to make sure that the byte past the end of the part you want in the std::string is 0, and that a 0 byte cannot appear elsewhere in the packet. This would break the conversion to/from std::string. If that is a problem, you may have to forgo the string representation and use the char array directly (along with a byte count).

Philip Nicoletti
February 17th, 2008, 12:28 PM
1) The code you posted can not compile. Is packet supposed to be
a stringstream ???

2) Assuming that packet is a stringstream, you are using operator << ...
which is formatted output.

3) Maybe you want unformatted IO


std::stringstream packet;

// packet << cat << chicken << monkey;

packet.write( reinterpret_cast<char*>(&cat),sizeof(cat) );
packet.write( reinterpret_cast<char*>(&chicken),sizeof(chicken) );
packet.write( reinterpret_cast<char*>(&monkey),sizeof(monkey) );


4) As mentioned above, using packet.str().c_str() might not show
everything in the stream.

MikeAThon
February 17th, 2008, 01:00 PM
Agree with Phillip: The OP is proabably thinking of a std::stringstream, not a std::string.

You can use string::append ( const char* s, size_t n ), to append arbitrary bytes to the end of a std::string, without the type of conversion to an ASCII representation that you are seeing by using the "<<" operator and std::stringstream.

Mike