Skip to content

Instantly share code, notes, and snippets.

@Hossara
Last active January 3, 2023 19:51
Show Gist options
  • Save Hossara/d64d0f241a69d2153a0ad23665058784 to your computer and use it in GitHub Desktop.
Save Hossara/d64d0f241a69d2153a0ad23665058784 to your computer and use it in GitHub Desktop.
Convert int & float to binary in python without using bin function
def trans(x):
if x == 0: return [0]
bit = []
while x:
bit.append(x % 2)
x >>= 1
arr = bit[::-1]
arr = list(map(str, arr))
return ''.join(arr)
def solve(number, places = 5):
if len(str(number).split(".")) > 1:
whole, dec = str(number).split(".")
whole = int(whole)
dec = int (dec)
res = trans(whole) + "."
for x in range(places):
whole, dec = str((decimal_converter(dec)) * 2).split(".")
dec = int(dec)
res += whole
return res
else:
return trans(int(number))
def decimal_converter(num):
while num > 1:
num /= 10
return num
n = input()
print(solve(n))
@Melanee-Melanee
Copy link

Perfect💥💥💥

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