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

前端 未结 3 1221
太阳男子
太阳男子 2020-12-20 03:43

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.s         


        
相关标签:
3条回答
  • 2020-12-20 04:07

    If you're targeting a little-endian architecture,

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

    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".

    0 讨论(0)
  • 2020-12-20 04:09

    repr() is your friend.

    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>
    
    0 讨论(0)
  • 2020-12-20 04:11

    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\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)
提交回复
热议问题