【问题标题】:How to convert a float into hex如何将浮点数转换为十六进制
【发布时间】:2014-05-13 06:32:32
【问题描述】:

在 Python 中,我需要将一堆浮点数转换为十六进制。它需要补零(例如,0x00000010 而不是 0x10)。就像http://gregstoll.dyndns.org/~gregstoll/floattohex/ 一样。 (遗憾的是我不能在我的平台上使用外部库,所以我不能使用该网站上提供的库)

最有效的方法是什么?

【问题讨论】:

  • 使用struct,然后提取字节。

标签: python python-2.7 floating-point-conversion


【解决方案1】:

这在 python 中有点棘手,因为不打算将浮点 转换为(十六进制)整数。相反,您尝试解释浮点值的IEEE 754 二进制表示为十六进制。

我们将使用内置 struct 库中的 packunpack 函数。

float 是 32 位的。我们首先将pack 转换为二进制1 字符串,然后将unpack 转换为int

def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])

float_to_hex(17.5)    # Output: '0x418c0000'

我们可以对double 做同样的事情,因为它是 64 位的:

def double_to_hex(f):
    return hex(struct.unpack('<Q', struct.pack('<d', f))[0])

double_to_hex(17.5)   # Output: '0x4031800000000000L'

1 - 表示一串原始字节; 不是一串一和零。

【讨论】:

  • 非常感谢。没有意识到我需要先将其转换为二进制。
【解决方案2】:

在 Python 中,float 始终是双精度的。

如果您需要以十六进制整数的形式输出答案,则该问题已得到解答:

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'

但是您可以考虑使用内置函数:

(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

这与以前的答案相同,只是采用了更结构化和更易于阅读的格式。

低 52 位是尾数。高 12 位由一个符号位和一个 11 位指数组成;指数偏差为 1023 == 0x3FF,因此 0x403 表示“4”。见Wikipedia article on IEEE floating point

【讨论】:

    【解决方案3】:

    进一步Jonathon Reinhart's 非常有帮助answer。我需要它通过 UDP 发送一个浮点数作为字节

    import struct
    
    # define double_to_hex (or float_to_hex)
    def double_to_hex(f):
        return hex(struct.unpack('<Q', struct.pack('<d', f))[0])
    
    # On the UDP transmission side
    doubleAsHex = double_to_hex(17.5)
    doubleAsBytes = bytearray.fromhex(doubleAsHex.lstrip('0x').rstrip('L'))
    
    # On the UDP receiving side
    doubleFromBytes = struct.unpack('>d', doubleAsBytes)[0] # or '>f' for float_to_hex
    

    【讨论】:

    • 谢谢,不幸的是这对我不起作用。二进制数组中的第一个字节不知何故丢失了。请参见下面的示例代码: import struct def double_to_hex(f): return hex(struct.unpack('
    • @user1323995 二进制数组中的第一个字节实际上可能没有丢失。由于 ASCII 编码并取决于您的 IDE,直接打印字节数组可能会导致非常误导的结果。给定您的示例 doubleAsHex = double_to_hex(2.1),在我的 Eclipse PyDev print(doubleAsBytes) 上给出 bytearray(b'@\x00\xcc\xcc\xcc\xcc\xcc\xcd')。尝试使用print(''.join('%02x,' % byte for byte in doubleAsBytes).rstrip(',')) 之类的东西,这给出了 40,00,cc,cc,cc,cc,cc,cd
    • 谢谢肯。确实如此。
    【解决方案4】:

    如果您使用的是 micropython(问题中没有说,但我找不到),您可以使用它

    import struct
    import binascii
    def float_to_hex(f):
        return binascii.hexlify(struct.pack('<f', f))
    float_to_hex(17.5) # 0x418c0000
    

    【讨论】:

      猜你喜欢
      • 2014-03-01
      • 2015-08-11
      • 2010-12-08
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      相关资源
      最近更新 更多