python把浮点数转换成16进制_如何将浮点数转换为十六进制

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)

What is the most efficient way of doing this?

解决方案

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.

We'll use the pack and unpack functions from the built-in struct library.

A float is 32-bits. We'll first pack it into a binary1 string, and then unpack it as an int.

def float_to_hex(f):

return hex(struct.unpack('

float_to_hex(17.5) # Output: '0x418c0000'

We can do the same for double, knowing that it is 64 bits:

def double_to_hex(f):

return hex(struct.unpack('

double_to_hex(17.5) # Output: '0x4031800000000000L'

1 - Meaning a string of raw bytes; not a string of ones and zeroes.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值