如何在Python中转换浮点数?

4

如何在Python中将浮点数转换为16进制数字,每个32位FLP数字有8个十六进制数字?

例如:输入=1.2717441261e+20 要输出:3403244E


3
这个输出是如何得出的? - glglgl
5个回答

11
如果你想要IEEE-754表示法的字节值,可以使用struct模块来实现: struct
>>> import struct
>>> f = 1.2717441261e+20
>>> struct.pack('f', f)
'\xc9\x9c\xdc`'

这是字节的字符串版本,可以将其转换为十六进制值的字符串表示:

>>> struct.pack('f', f).encode('hex')
'c99cdc60'

而且,如果你想将它转换为十六进制整数,请解析它:

>>> s = struct.pack('f', f).encode('hex')
>>> int(s, 16)
3382500448

要将整数显示为十六进制:

>>> hex(int(s, 16))
'0xc99cdc60'
请注意,这不符合您问题中的十六进制值--如果您的值是正确的值,请更新问题说明它是如何得出的。

为了让代码在Python 3中正常工作,请使用codecs.encode(pack('f', f), 'hex') - Björn Lindqvist
1
从Python3.5开始,似乎字节对象包含一个hex()方法,因此上面的第一个示例可以简化为struct.pack('f', f).hex() - anirudh

4
有几种可能的方法可以达到这个目的,但是没有一种方法会导致你想要的结果。
  • You can code this float value into its IEEE binary representation. This leads indeed to a 32 bit number (if you do it with single precision). But it leads to different results, no matter which endianness I suppose:

    import struct
    struct.pack("<f", 1.2717441261e+20).encode("hex")
    # -> 'c99cdc60'
    struct.pack(">f", 1.2717441261e+20).encode("hex")
    # -> '60dc9cc9'
    
    struct.unpack("<f", "3403244E".decode("hex"))
    # -> (687918336.0,)
    struct.unpack(">f", "3403244E".decode("hex"))
    # -> (1.2213533295835077e-07,)
    
  • As the other one didn't fit result-wise, I'll take the other answers and include them here:

    float.hex(1.2717441261e+20)
    # -> '0x1.b939919e12808p+66'
    

    Has nothing to do with 3403244E as well, so maybe you want to clarify what exactly you mean.

当然,还有其他方法来进行这种对话,但是除非您指定您希望使用的方法,否则没有人可能能够帮助您。


1
您期望的输出有问题:
import struct
input = 1.2717441261e+20
buf = struct.pack(">f", input)
print ''.join("%x" % ord(c) for c in struct.unpack(">4c", buf) )

输出:
60dc9cc9

这取决于您如何打包和解包字节,但我不知道您如何获得所提到的输出。 - Emil Davtyan

1
尝试使用float.hex(input)。这应该将数字转换为表示16进制数字的字符串,并且与浮点数一起使用,不像hex()。但是,该字符串将以0x开头,并且小数点后面将包含13个数字,因此我无法帮助您处理8个数字部分。
来源:http://docs.python.org/2/library/stdtypes.html#float.hex

仅适用于整数。 - RamPrasadBismil
那个数字是如何转换成3403244E的?我不太理解,也许我能更好地回答这个问题。谢谢! - Impossibility

0
如果输入已经是浮点数,请尝试使用 float.hex(input)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接