rfmonk

floating point hex to binary

Dec 18th, 2012
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. #! /usr/bin/env python
  2.  
  3. def convertFloatBin(num):
  4.     exponent=0
  5.     shifted_num=num
  6.     while shifted_num != int(shifted_num):
  7.         shifted_num*=2
  8.         exponent+=1
  9.     if exponent==0:
  10.         return '{0:0b}'.format(int(shifted_num))
  11.     binary='{0:0{1}b}'.format(int(shifted_num),exponent+1)
  12.     integer_part=binary[:-exponent]
  13.     fractional_part=binary[-exponent:].rstrip('0')
  14.     return '{0}.{1}'.format(integer_part, fractional_part)
  15.  
  16. def floathex_to_binary(floathex):
  17.     num = float.fromhex(floathex)
  18.     return floathex_to_binary(num)
  19.  
  20. print(floathex_to_binary('0x1.ccccccccccccdp+2'))
  21.  
  22. print(floathex_to_binary('0x1.ccccccccccccdp+1'))
  23.  
  24. # this doesn't work
  25. # I want to take the float 0.9 converted to hex 0x1.ccccccccccccdp-1
  26. # and convert it to a binary representation. I'll come back later
  27. # when my maths have improved.
Advertisement
Add Comment
Please, Sign In to add comment