C
Carsten Fuchs
Dear group,
I would like to serialize a float f1 to a string s, then unserialize s back to a float f2 again,
such that:
* s is minimal (use only the precision that is required)
and preferably in decimal notation,
* f1==f2 (exact same value after the roundtrip)
(The first property is for human readers and file size, the second is for data integrity.)
Here is my implementation:
std::string serialize(float f1)
{
std::string s;
for (unsigned int prec=6; prec<10; prec++)
{
std::stringstream ss;
ss.precision(prec);
ss << f1;
s=ss.str();
float f2;
ss >> f2;
if (f2==f1) break;
}
return s;
}
It seems to work very well, and I found that in my application 65% to 90% of the float numbers
serialized this way exit the loop in the first iteration.
However, I was wondering if there is a shorter and/or more elegant way of implementing this,
using either C++ streams, C printf-functions, or any other technique available in C++.
I'd be very grateful for any feedback and advice!
Thank you very much, and best regards,
Carsten
I would like to serialize a float f1 to a string s, then unserialize s back to a float f2 again,
such that:
* s is minimal (use only the precision that is required)
and preferably in decimal notation,
* f1==f2 (exact same value after the roundtrip)
(The first property is for human readers and file size, the second is for data integrity.)
Here is my implementation:
std::string serialize(float f1)
{
std::string s;
for (unsigned int prec=6; prec<10; prec++)
{
std::stringstream ss;
ss.precision(prec);
ss << f1;
s=ss.str();
float f2;
ss >> f2;
if (f2==f1) break;
}
return s;
}
It seems to work very well, and I found that in my application 65% to 90% of the float numbers
serialized this way exit the loop in the first iteration.
However, I was wondering if there is a shorter and/or more elegant way of implementing this,
using either C++ streams, C printf-functions, or any other technique available in C++.
I'd be very grateful for any feedback and advice!
Thank you very much, and best regards,
Carsten