How to convert a float into hex

后端 未结 4 1490
情话喂你
情话喂你 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:33

    This is a bit tricky in python, because aren't looking to convert the floating-point value to a (hex) integer. Instead, you're trying to interpret the IEEE 754 binary representation of the floating-point value as hex.

    We'll use the pack and unpack functions from the built-in struct library.

    A float is 32-bits. We'll first pack it into a binary1 string, and then unpack it as an int.

    def float_to_hex(f):
        return hex(struct.unpack('

    We can do the same for double, knowing that it is 64 bits:

    def double_to_hex(f):
        return hex(struct.unpack('

    1 - Meaning a string of raw bytes; not a string of ones and zeroes.

提交回复
热议问题