In Python 2.5, I have a float and I\'d like to obtain and manipulate its bit pattern as an integer.
For example, suppose I have
x = 173.3125
<
The problem is that a Python float object might not be a IEEE 754, because it is an object (in fact they are, but internally they could hold whichever representation is more convenient)...
As leo said, you can do a type cast with ctypes, so you are enforcing a particular representation (in this case, single precision):
from ctypes import *
x = 173.3125
bits = cast(pointer(c_float(x)), POINTER(c_int32)).contents.value
print hex(bits)
#swap the least significant bit
bits ^= 1
And then back:
y = cast(pointer(c_int32(bits)), POINTER(c_float)).contents.value