Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

easy hex/float conversion

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!

like image 860
user290494 Avatar asked Mar 23 '26 04:03

user290494


1 Answers

From the link you provided in your question (Additional Methods on Float):

This syntax is similar to the syntax specified in section 6.4.4.2 of the C99 standard, and also to the syntax used in Java 1.5 onwards. In particular, the output of float.hex() is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C’s %a format character or Java’s Double.toHexString are accepted by float.fromhex().

Example:

#include <cstdio>

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

Run it:

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

Output:

42.79 == 0x1.5651ecp+5
12.34 == 0x1.8ae148p+3
like image 162
jfs Avatar answered Mar 24 '26 17:03

jfs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!