如何在Python中将浮点数转换为16进制数字,每个32位FLP数字有8个十六进制数字?
例如:输入=1.2717441261e+20 要输出:3403244E
如何在Python中将浮点数转换为16进制数字,每个32位FLP数字有8个十六进制数字?
例如:输入=1.2717441261e+20 要输出:3403244E
>>> 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'
请注意,这不符合您问题中的十六进制值--如果您的值是正确的值,请更新问题说明它是如何得出的。codecs.encode(pack('f', f), 'hex')
。 - Björn Lindqvisthex()
方法,因此上面的第一个示例可以简化为struct.pack('f', f).hex()
。 - anirudhYou 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.
当然,还有其他方法来进行这种对话,但是除非您指定您希望使用的方法,否则没有人可能能够帮助您。
import struct
input = 1.2717441261e+20
buf = struct.pack(">f", input)
print ''.join("%x" % ord(c) for c in struct.unpack(">4c", buf) )
60dc9cc9
float.hex(input)
。这应该将数字转换为表示16进制数字的字符串,并且与浮点数一起使用,不像hex()
。但是,该字符串将以0x
开头,并且小数点后面将包含13个数字,因此我无法帮助您处理8个数字部分。float.hex(input)
。