Last active
August 29, 2015 14:02
-
-
Save zvyn/de577d83ab9633928c5e to your computer and use it in GitHub Desktop.
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
#!/bin/env python | |
import logging | |
def float_to_bin(x): | |
p = 0 | |
while ((2 ** p) * x) % 1 != 0: | |
logging.info('Remainder = %s' % ((2 ** p) * x - int((2 ** p) * x))) | |
p += 1 | |
num = int(x * (2 ** p)) | |
result = '0' if num == 0 else '' | |
while num > 0: | |
result = str(num % 2) + result | |
num = int(num / 2) | |
for i in range(p - len(result)): | |
result = '0' + result | |
return '%s.%s' % ((result, 0) if p == 0 else (result[0:-p], result[-p:])) | |
if __name__ == '__main__': | |
logging.basicConfig(level=logging.INFO, format='%(message)s') | |
print(float_to_bin(float(input('Enter a number: ')))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment