Skip to content

Instantly share code, notes, and snippets.

@spdin
Last active October 31, 2019 10:53
Show Gist options
  • Save spdin/f889a3b92222de71e317a05217aad0e0 to your computer and use it in GitHub Desktop.
Save spdin/f889a3b92222de71e317a05217aad0e0 to your computer and use it in GitHub Desktop.
IEEE 754 Converter
# https://stackoverflow.com/questions/8751653/how-to-convert-a-binary-string-into-a-float-value
# http://weitz.de/ieee/
from codecs import decode
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, length): # Helper function
""" Int/long to byte string.
Python 3.2+ has a built-in int.to_bytes() method that could be used
instead, but the following works in earlier versions including 2.x.
"""
return decode('%%0%dx' % (length << 1) % n, 'hex')[-length:]
def float_to_bin(value): # For testing.
""" Convert float to 64-bit binary string. """
[d] = struct.unpack(">Q", struct.pack(">d", value))
return '{:064b}'.format(d)
if __name__ == '__main__':
for f in 0.0, 1.0, -14.0, 12.546, 3.141593:
print('Test value: %f' % f)
binary = float_to_bin(f)
print(' float_to_bin: %r' % binary)
floating_point = bin_to_float(binary) # Round trip.
print(' bin_to_float: %f\n' % floating_point)
@spdin
Copy link
Author

spdin commented Oct 31, 2019

scale = 16
num_of_bits=64

bin_to_float(bin(int('0x4085f63d70a3d70b' , scale))[2:].zfill(num_of_bits))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment