问题描述
在Python中,我需要将一堆浮点数转换为十六进制.必须填充为零(例如0x00000010而不是0x10).就像 http://gregstoll.dyndns.org/~gregstoll/floattohex/一样. (遗憾的是,我无法在平台上使用外部库,因此无法使用该网站上提供的库)
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/~gregstoll/floattohex/ does. (sadly i can't use external libs on my platform so i can't use the one provided on that website)
最有效的方法是什么?
推荐答案
这在python中有点棘手,因为它不希望将浮点 value 转换为(十六进制)整数.相反,您尝试解释 IEEE 754 的二进制表示形式浮点值为十六进制.
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.
我们将使用内置的 struct
库.
We'll use the pack
and unpack
functions from the built-in struct
library.
A float
是32位.我们首先将其pack
转换为二进制字符串,然后将unpack
用作int
.
A float
is 32-bits. We'll first pack
it into a binary string, and then unpack
it as an 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位:
We can do the same for double
, knowing that it is 64 bits:
def double_to_hex(f):
return hex(struct.unpack('<Q', struct.pack('<d', f))[0])
double_to_hex(17.5) # Output: '0x4031800000000000L'
这篇关于如何将浮点数转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!