Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

double - How do I convert a Python float to a hexadecimal string in python 2.5? Nonworking solution attached

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
", xf);
  return 0;
}

But in C I get:

7385687666638364672.000000 and not sqrt(2).

What am I missing?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 a double. If you throw some pointers/addressing at it it works:

jkugelman$ cat float.c
#include <stdio.h>

int main(void)
{
    unsigned long x[2] = {1719614413, 1073127582};
    double d = *(double *) x;

    printf("%f
", d);
    return 0;
}
jkugelman$ gcc -o float float.c 
jkugelman$ ./float 
1.414214

Notice also that the format specifier for double (and for float) is %f, not %lf. %lf is for long double.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...