Last active
October 31, 2019 10:53
-
-
Save spdin/f889a3b92222de71e317a05217aad0e0 to your computer and use it in GitHub Desktop.
IEEE 754 Converter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
scale = 16
num_of_bits=64
bin_to_float(bin(int('0x4085f63d70a3d70b' , scale))[2:].zfill(num_of_bits))