How to convert a float into hex

后端 未结 4 1496
情话喂你
情话喂你 2020-12-02 21:02

In Python I need to convert a bunch of floats into hexadecimal. It needs to be zero padded (for instance, 0x00000010 instead of 0x10). Just like http://gregstoll.dyndns.org/

4条回答
  •  星月不相逢
    2020-12-02 21:37

    In Python float is always double-precision.

    If you require your answer to be output in the form of a hexadecimal integer, the question was already answered:

    import struct
    
    # define double_to_hex as in the other answer
    
    double_to_hex(17.5)   # Output: '0x4031800000000000'
    double_to_hex(-17.5)  # Output: '0xc031800000000000'
    

    However you might instead consider using the builtin function:

    (17.5).hex()    # Output: '0x1.1800000000000p+4'
    (-17.5).hex()   # Output: '-0x1.1800000000000p+4'
    
    # 0x1.18p+4 == (1 + 1./0x10 + 8./0x100) * 2**4 == 1.09375 * 16 == 17.5
    

    This is the same answer as before, just in a more structured and human-readable format.

    The lower 52 bits are the mantissa. The upper 12 bits consists of a sign bit and an 11-bit exponent; the exponent bias is 1023 == 0x3FF, so 0x403 means '4'. See Wikipedia article on IEEE floating point.

提交回复
热议问题