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
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?
For reference, it is also possible to use numpy and view.
import numpy
def fextract( f ):
bits = numpy.asarray( f, dtype=numpy.float64 ).view( numpy.int64 )
if not bits & 0x7fffffffffffffff: # f == +/-0
return 0, 0
sign = numpy.sign(bits)
exponent = ( (bits>>52) & 0x7ff ) - 1075
mantissa = 0x10000000000000 | ( bits & 0xfffffffffffff )
# from here on f == sign * mantissa * 2**exponent
for shift in 32, 16, 8, 4, 2, 1:
if not mantissa & ((1<<shift)-1):
mantissa >>= shift
exponent += shift
return sign * mantissa, exponent
fextract( 1.5 ) # --> 3, -1
Use struct
or xdrlib
module:
>>> import struct
>>> x = 173.3125
>>> rep = struct.pack('>f', x)
>>> numeric = struct.unpack('>I', rep)[0]
>>> '%x' %numeric
'432d5000'
Now you can work with numeric
, and then go in the reverse direction to get your floating point number back. You have to use >I (unsigned int) to avoid getting a negative number. xdrlib
is similar.
References: struct, xdrlib.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With