python四字节十六进制float_如何将Python float转换为python 2.5中的十六进制字符串?附加非工作解决方案...

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

#include

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

jkugelman$ cat float.c

#include

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值