What I really need to do is to export a floating point number to C with no precision loss.
I did this in python:
import math
import struct
x = math.sqrt(2)
print struct.unpack('ii', struct.pack('d', x))
# prints (1719614413, 1073127582)
And in C I try this:
#include <math.h>
#include <stdio.h>
int main(void)
{
unsigned long long x[2] = {1719614413, 1073127582};
long long lx;
double xf;
lx = (x[0] << 32) | x[1];
xf = (double)lx;
printf("%lf\n", xf);
return 0;
}
But in C I get:
7385687666638364672.000000 and not sqrt(2).
What am I missing?
Thanks.
The Python code appears to work. The problem is in the C code: you have the
long long
filled out right, but then you convert the integer value directly into floating point, rather than reinterpreting the bytes as adouble
. If you throw some pointers/addressing at it it works:Notice also that the format specifier for
double
(and forfloat
) is%f
, not%lf
.%lf
is forlong double
.If you're targeting a little-endian architecture,
if big-endian, use
'>d'
instead of<d
. In either case, this gives you a hex string as you're asking for in the question title's, and of course C code can interpret it; I'm not sure what those two ints have to do with a "hex string".repr() is your friend.