I am doing some input/output between a c++ and a python program (only floating point values) python has a nice feature of converting floating point values to hex-numbers and back as you can see in this link:
http://docs.python.org/library/stdtypes.html#additional-methods-on-float
Is there an easy way in C++ to to something similar? and convert the python output back to C++ double/float? This way I would not have the problem of rounding errors when exchanging data between the two processes...
thx for the answers!
C++11 offers std::hexfloat: IO manipulators including hexfloat
If you can use C++11 then hexfloat is pretty easy to use.
From the link you provided in your question (Additional Methods on Float):
Example:
Run it:
Output:
You're sorely mistaken if you believe that this will solve all your problems. The hex notation is exactly equivalent to the original float. It just uses a different representation.
The docs there say that
%a
does this in C.C++ does not have any library routines for converting hex to floating point. One reason is that the internal representation of floating point is not standardized (although many compilers do use an IEEE standard).
I recommend storing in ASCII format, which is portable across platforms. You could write your own library (or find another) which will convert between an IEEE format (in hex) to the internal representation.
If you're on a platform whose system C library supports C99, you can just use
printf( )
andscanf( )
with the%a
format specifier. For reading in such values, you can also use the C99strtod( )
,strtof( )
, andstrtold( )
functions:You can optionally replace
NULL
with achar **
to get back a pointer to the end of the sequence of converted characters, and0
with a known base for the string representation (if you set the base to be zero, it will infer the base from the format; it will parse the python hex floats just fine, and also handle normal decimal-formatted floating point)If your compiler/library vendor has chosen not to care about C99 (MSVC, basically), you're probably out of luck until these function are incorporated into the C++ standard (I believe that they're in the draft C++0x, but I'm not completely sure).