-
December 13th, 2011, 09:15 AM
#1
Can I serialize floats over a TCP/IP link with stringstream?
Greetings,
Can you use stringstreams to serialize say floats over a tcp/ip link? will this work?
sender:
Code:
ostringstream oss;
float f1 = 3.2134f;
float f2 = 0.1123f;
oss << setw(5) << setprecision(4) << f1 << " " << f2;
...
tcpConnection->Send(oss.str().c_str(), oss.str().size());
...
receiver:
Code:
...
string message = tcpConnection->Receive();
...
istringstream iss(message);
iss >> f1 >> f2;
Last edited by ekhule; December 13th, 2011 at 09:39 AM.
-
December 13th, 2011, 10:56 AM
#2
Re: Can I serialize floats over a TCP/IP link with stringstream?
Have you already tried it ?
-
December 13th, 2011, 11:09 AM
#3
Re: Can I serialize floats over a TCP/IP link with stringstream?
Originally Posted by ekhule
Greetings,
Can you use stringstreams to serialize say floats over a tcp/ip link? will this work?
sender:
Code:
ostringstream oss;
float f1 = 3.2134f;
float f2 = 0.1123f;
oss << setw(5) << setprecision(4) << f1 << " " << f2;
...
tcpConnection->Send(oss.str().c_str(), oss.str().size());
...
receiver:
Code:
...
string message = tcpConnection->Receive();
...
istringstream iss(message);
iss >> f1 >> f2;
It might be a little sub-efficient, but it is portable and "works". You'll lose some of the precision with that setup though.
A float has approximatly 23 bits of binary precision, which is roughly equivalent to 7 decimal digits. A double is precise up to about 16 decimals.
I'd use "setprecision(20)".
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
-
December 13th, 2011, 09:57 PM
#4
Re: Can I serialize floats over a TCP/IP link with stringstream?
Sure, that should work. If you are talking with servers, it is more common to use a standard serialization scheme like xml, json, yaml, imap, but for simple things that don't need to be portable to other systems, that will work just fine.
Will tcpConnection->Receive() return a string or binary? I only ask because you do not send the null terminator of the c_str. If it simply dumps out the raw data exactly how it goes in, then you will cause corruption, so send size() + 1 bytes, otherwise, it's fine.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|