[英]How do I convert a Python float to a hexadecimal string in python 2.5? Nonworking solution attached
我真正需要做的是將浮點數導出到C而沒有精度損失。
我在python中這樣做了:
import math
import struct
x = math.sqrt(2)
print struct.unpack('ii', struct.pack('d', x))
# prints (1719614413, 1073127582)
在CI中試試這個:
#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;
}
但在CI獲得:
7385687666638364672.000000而不是sqrt(2)。
我錯過了什么?
謝謝。
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
。
如果你的目標是小端架構,
>>> s = struct.pack('<d', x)
>>> ''.join('%.2x' % ord(c) for c in s)
'cd3b7f669ea0f63f'
如果是big-endian,請使用'>d'
而不是<d
。 在任何一種情況下,這都會給你一個十六進制字符串,正如你在問題標題中所要求的那樣,當然C代碼可以解釋它; 我不確定這兩個整數與“十六進制字符串”有什么關系。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.