如何将浮点数转换为十六进制

use*_*945 16 python python-2.7 floating-point-conversion

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

这样做最有效的方法是什么?

Jon*_*art 36

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

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

A 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'
Run Code Online (Sandbox Code Playgroud)

我们可以这样做double,因为它知道它是64位:

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

double_to_hex(17.5)   # Output: '0x4031800000000000L'
Run Code Online (Sandbox Code Playgroud)

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


gho*_*ter 14

在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'
Run Code Online (Sandbox Code Playgroud)

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

(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
Run Code Online (Sandbox Code Playgroud)

这与以前的答案相同,只是采用更加结构化和人类可读的格式.

低52位是尾数.高12位由符号位和11位指数组成; 指数偏差为1023 == 0x3FF,因此0x403表示'4'.请参阅Wikipedia关于IEEE浮点的文章.


Ken*_*Ken 6

乔纳森·莱因哈特 (Jonathon Reinhart) 的非常有用的回答之后。我需要这个来通过 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
Run Code Online (Sandbox Code Playgroud)


小智 5

如果你使用的是 micropython (问题中没有提到,但我很难找到)你可以使用这个

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