Easy conversion with hex / floating

I am doing some input / output between C ++ and a python program (only floating point values). python has a nice function for converting floating point values ​​to hexadecimal numbers and vice versa, as you can see from this link:

http://docs.python.org/library/stdtypes.html#additional-methods-on-float

Is there an easy way in C ++ for something like this? and convert python output back to c ++ double / float? That way, I would not have a problem with rounding errors when exchanging data between two processes ...

thanks for the answers!

+2
source share
7 answers

, ( ):

6.4.4.2 C99, Java 1.5 . , float.hex() C Java Cs% - Javas Double.toHexString float.fromhex().

:

#include <cstdio>

int main() {
  float f = 42.79;
  printf("%.2f == %a\n", f, f);  
  fscanf(stdin, "%a", &f);
  printf("%.2f == %a\n", f, f);  
}

:

$ g++ *.cpp && (python -c'print 12.34.hex()' | ./a.out )

:

42.79 == 0x1.5651ecp+5
12.34 == 0x1.8ae148p+3
+5

? struct Python Python.

+2

, %a C.

+1

, , . . .

+1

++ - hex . , ( IEEE).

ASCII, . ( ), IEEE ( ) .

+1

, C C99, printf( ) scanf( ) %a. C99 strtod( ), strtof( ) strtold( ):

float value = strtof(string, NULL, 0);

NULL char **, , 0 ( , , python , )

If your compiler / library provider decided not to care about C99 (MSVC, mostly), you probably weren't lucky until these functions are included in the C ++ standard (I believe they are in the C ++ 0x project, but I'm not quite sure).

+1
source

C ++ 11 offers std :: hexfloat: IO manipulators, including hexfloat

If you can use C ++ 11 then hexfloat is pretty easy to use.

0
source

All Articles