Advertisement
Guest User

Untitled

a guest
Aug 31st, 2016
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. TypeError: string argument without an encoding
  2.  
  3. import struct
  4.  
  5. def bin_to_float(b):
  6. """ Convert binary string to a float. """
  7. bf = int_to_bytes(int(b, 2), 8) # 8 bytes needed for IEEE 754 binary64
  8. return struct.unpack('>d', bf)[0]
  9.  
  10. def int_to_bytes(n, minlen=0): # helper function
  11. """ Int/long to byte string. """
  12. nbits = n.bit_length() + (1 if n < 0 else 0) # plus one for any sign bit
  13. nbytes = (nbits+7) // 8 # number of whole bytes
  14. bytes = []
  15. for _ in range(nbytes):
  16. bytes.append(chr(n & 0xff))
  17. n >>= 8
  18. if minlen > 0 and len(bytes) < minlen: # zero pad?
  19. bytes.extend((minlen-len(bytes)) * '0')
  20. return ''.join(reversed(bytes)) # high bytes at beginning
  21.  
  22. # tests
  23.  
  24. def float_to_bin(f):
  25. """ Convert a float into a binary string. """
  26. ba = struct.pack('>d', f)
  27. ba = bytearray(ba)
  28. s = ''.join('{:08b}'.format(b) for b in ba)
  29. s = s.lstrip('0') # strip leading zeros
  30. return s if s else '0' # but leave at least one
  31.  
  32. for f in 0.0, 1.0, -14.0, 12.546, 3.141593:
  33. binary = float_to_bin(f)
  34. print('float_to_bin(%f): %r' % (f, binary))
  35. float = bin_to_float(binary)
  36. print('bin_to_float(%r): %f' % (binary, float))
  37. print('')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement