取得&将float的位模式操作为整数 [英] Obtain & manipulate bit pattern of float as integer

查看:69
本文介绍了取得&将float的位模式操作为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2.5中,我有一个浮点数,我想获取并操纵其位模式为整数.

In Python 2.5, I have a float and I'd like to obtain and manipulate its bit pattern as an integer.

例如,假设我有

x = 173.3125

在IEEE 754格式中,x的十六进制位模式为432D5000.

In IEEE 754 format, x's bit pattern in hexadecimal is 432D5000.

我如何获得&在该位模式上进行操作(例如执行按位操作)?

How can I obtain & manipulate (e.g., perform bitwise operations) on that bit pattern?

推荐答案

您可以获取所需的字符串(显然是32位大端字节表示; Python内部使用本地字节序和64位浮点数)使用struct模块:

You can get the string you want (apparently implying a big-endian, 32-bit representation; Python internally uses the native endianity and 64-bits for floats) with the struct module:

>>> import struct
>>> x = 173.125
>>> s = struct.pack('>f', x)
>>> ''.join('%2.2x' % ord(c) for c in s)
'432d2000'

这还不能让您执行按位运算,但是您可以再次使用struct将字符串映射到int:

this doesn't yet let you perform bitwise operations, but you can then use struct again to map the string into an int:

>>> i = struct.unpack('>l', s)[0]
>>> print hex(i)
0x432d2000

现在您可以使用int进行任何按位操作(如果执行上述操作后,您需要再次获取float,则可以按照相反的两个步骤进行操作).

and now you have an int which you can use in any sort of bitwise operations (follow the same two steps in reverse if after said operations you need to get a float again).

这篇关于取得&将float的位模式操作为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆