Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- TypeError: string argument without an encoding
- import struct
- def bin_to_float(b):
- """ Convert binary string to a float. """
- bf = int_to_bytes(int(b, 2), 8) # 8 bytes needed for IEEE 754 binary64
- return struct.unpack('>d', bf)[0]
- def int_to_bytes(n, minlen=0): # helper function
- """ Int/long to byte string. """
- nbits = n.bit_length() + (1 if n < 0 else 0) # plus one for any sign bit
- nbytes = (nbits+7) // 8 # number of whole bytes
- bytes = []
- for _ in range(nbytes):
- bytes.append(chr(n & 0xff))
- n >>= 8
- if minlen > 0 and len(bytes) < minlen: # zero pad?
- bytes.extend((minlen-len(bytes)) * '0')
- return ''.join(reversed(bytes)) # high bytes at beginning
- # tests
- def float_to_bin(f):
- """ Convert a float into a binary string. """
- ba = struct.pack('>d', f)
- ba = bytearray(ba)
- s = ''.join('{:08b}'.format(b) for b in ba)
- s = s.lstrip('0') # strip leading zeros
- return s if s else '0' # but leave at least one
- for f in 0.0, 1.0, -14.0, 12.546, 3.141593:
- binary = float_to_bin(f)
- print('float_to_bin(%f): %r' % (f, binary))
- float = bin_to_float(binary)
- print('bin_to_float(%r): %f' % (binary, float))
- print('')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement