Skip to content

Instantly share code, notes, and snippets.

@PatchRowcester
Created February 27, 2013 03:34
Show Gist options
  • Save PatchRowcester/5044803 to your computer and use it in GitHub Desktop.
Save PatchRowcester/5044803 to your computer and use it in GitHub Desktop.
This is a way to convert a number between 0 & 1 to its binary form in Python
x = float(raw_input('Enter a number between 0 and 1: '))
p = 0
#if a number is a whole number, the reminder when divided by 1 is always 0
#if a number is not a whole number, the reminder when divided by 1 is NOT 0
#Because we are trying to convert a decimal to a whole number, this check is necessary
while (((2**p) * x)%1 !=0):
print('Remainder = ' + str((2**p)*x - int((2**p)*x)))
p += 1
num = int(x*(2**p))
print str(p)
result =''
if num ==0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num/2
#This is division by 2^p in base 2. This basically means moving the decimal point to 2^p position to the left
for i in range(p-len(result)):
result = '0'+ result
#this is the original way to place decimal point
result = result[0:-p] + '.' + result[-p:]
#this is bascially placing the decimal point at the beginning of 'result'
#result = result[0:0] + '.'+ result
print('The binary representation of ' + str(x) + ' is ' + str(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment