的Python:获得&放大器;操作(整型)浮标位模式 [英] Python: obtain & manipulate (as integers) bit patterns of floats
问题描述
在Python中V.2.5.4,我有一个浮动的,我想获得和操作(作为一个整数)花车的位模式。
In Python V.2.5.4, I have a float, and I'd like to obtain and manipulate (as an integer) the bit pattern of that float.
例如,假设我有
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位重presentation字符串; Python的内部使用本地endianity和64与结构
模块花车位):
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'
这还不让你执行位操作,但你可以再使用结构再串入一个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
您可以在任何类型的按位运算的使用(请以相反两个相同的步骤,如果说你需要获得一个操作后,浮动
再次)。
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).
这篇关于的Python:获得&放大器;操作(整型)浮标位模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!