Wednesday, December 12, 2012

hex2float.py

Quick an dirty hex2float python code.

Useful for taking a hexadecimal value and turn it into a floating point, this follow IEEE 754 and understanding of C99 Standard Section 6.4.4.2.



  # Assuming a hexadecimal value passed in, print out the
  # floating point equivalent. Can then use things like
  # float.hex(), float.fromhex() etc.
  1 def hex2float(hex):
  2   h = int(hex)
  3   sign = ((h >> 31) & 0x1)
  4   exp  = (h >> 23) & 0xff
  5
  6   ctr = 1
  7   mantissa = 0.0 if (exp-127) == -127 else 1.0  # Per IEEE 754
  8   while ctr <= 23:
  9     mantissa += ((h >> (23 - ctr) & 0x1) * (2**(-ctr)))
 10     ctr += 1
 11
 12   result = ( ((-1)**sign) * (mantissa) * (2**(exp-127)) )
 13   print "result = %s" % (result)