在Python 2.5中,如何将Python浮点转换为十六进制字符串?附加非工作溶液

2024-05-23 15:09:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我真正需要做的是将一个浮点数导出到C,而不丢失精度。

我用python做的:

import math
import struct
x = math.sqrt(2)
print struct.unpack('ii', struct.pack('d', x))
# prints (1719614413, 1073127582)

在C语言中,我尝试:

#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;
}

但在C中我得到:

7385687666638364672.000000,非sqrt(2)。

我错过了什么?

谢谢。


Tags: importinclude精度mathsqrtstructpacklong
3条回答

repr()是你的朋友。

C:\junk\es2>type es2.c
#include <stdio.h>
#include <math.h>
#include <assert.h>

int main(int argc, char** argv) {
    double expected, actual;
    int nconv;
    expected = sqrt(2.0);
    printf("expected: %20.17g\n", expected);
    actual = -666.666;
    nconv = scanf("%lf", &actual);
    assert(nconv == 1);
    printf("actual:   %20.17g\n", actual);
    assert(actual == expected);
    return 0;
    }


C:\junk\es2>gcc es2.c

C:\junk\es2>\python26\python -c "import math; print repr(math.sqrt(2.0))" | a
expected:   1.4142135623730951
actual:     1.4142135623730951

C:\junk\es2>

如果你的目标是一个小的endian架构

>>> s = struct.pack('<d', x)
>>> ''.join('%.2x' % ord(c) for c in s)
'cd3b7f669ea0f63f'

如果是big endian,请使用'>d',而不是<d。不管是哪种情况,这都会给你一个十六进制字符串,就像你在题目中要求的那样,当然C代码可以解释它;我不确定这两个int与“十六进制字符串”有什么关系。

Python代码似乎可以工作。问题出在C代码中:您已经把long long填好了,但是随后您直接将整数值转换成浮点,而不是将字节重新解释为double。如果你向它抛出一些指针/地址,它就会工作:

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

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

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

还要注意,double(和float)的格式说明符是%f,而不是%lf%lf用于long double

相关问题 更多 >