Skip to content

Instantly share code, notes, and snippets.

@constructor-s
Created October 17, 2020 19:56
Show Gist options
  • Save constructor-s/347291166a50fca8d4dd7130b9282700 to your computer and use it in GitHub Desktop.
Save constructor-s/347291166a50fca8d4dd7130b9282700 to your computer and use it in GitHub Desktop.
See the representation of a floating point in Python
import struct
num = 0.5
bits = [[c>>i & 1 for i in range(7, -1, -1)] for c in struct.pack("!d", num)]
bits_flatten = [i for l in bits for i in l]
bits_sign = bits_flatten[0]
bits_exponent = bits_flatten[1:12]
bits_fraction = bits_flatten[12:64]
sign = (-1) ** bits_sign
exponent = sum([b<<i for i, b in enumerate(reversed(bits_exponent))]) - 1023
fraction = 1 + sum([b*(2**(-(i+1))) for i, b in enumerate(bits_fraction)])
print(sign * fraction * (2**exponent))
@constructor-s
Copy link
Author

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