Skip to content

Instantly share code, notes, and snippets.

@RustemB
Last active November 15, 2018 16:51
Show Gist options
  • Save RustemB/a1de68aafd72e6e32239252d47611671 to your computer and use it in GitHub Desktop.
Save RustemB/a1de68aafd72e6e32239252d47611671 to your computer and use it in GitHub Desktop.
Convert decimal to binary
from decimal import Decimal as D
from math import pi, e
def convert(n, d=8):
"""
convert decimal to binary
"""
res = bin(int(n))[2:] + "."
x = D(n - int(n))
while d != 0:
x *= 2
res += str((x % 2).to_integral_value())
d -= 1
return res
tests = [1.5, 3.65, 12.12, pi, e]
for test in tests:
print(convert(test))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment