Last active
January 3, 2023 19:51
-
-
Save Hossara/d64d0f241a69d2153a0ad23665058784 to your computer and use it in GitHub Desktop.
Convert int & float to binary in python without using bin function
This file contains 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
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfect💥💥💥