Created
February 13, 2013 11:51
-
-
Save nafu/4944095 to your computer and use it in GitHub Desktop.
Decimal to Binary
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
num = 256 | |
if num < 0: | |
isNeg = True | |
num = abs(num) | |
else: | |
isNeg = False | |
result = '' | |
if num == 0: | |
result = '0' | |
while num > 0: | |
result = str(num%2) + result | |
num = num/2 | |
if isNeg: | |
result = '-' + result | |
print(result) |
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
x = float(raw_input('Enter a decimal number between 0 and 1: ')) | |
p = 0 | |
while ((2**p)*x)%1 !=0: | |
print('Remember = ' + str((2**p)*x - int(2**p)*x)) | |
p += 1 | |
num = int(x*(2**p)) | |
result = '' | |
if num == 0: | |
result = '0' | |
while num > 0: | |
result = str(num%2) + result | |
num = num/2 | |
for i in range(p - len(result)): | |
result = '0' + result | |
result = result[0:-p] + '' + result[-p:] | |
print('The binary representation of the decimal ' + str(x) + ' is .' + str(result)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment