Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain & manipulate bit pattern of float as integer

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?

like image 436
JaysonFix Avatar asked Dec 17 '09 16:12

JaysonFix


2 Answers

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
like image 64
gertjan Avatar answered Sep 19 '22 21:09

gertjan


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.

like image 40
Alok Singhal Avatar answered Sep 18 '22 21:09

Alok Singhal