Created
February 28, 2013 04:00
-
-
Save PatchRowcester/5054064 to your computer and use it in GitHub Desktop.
This python program will convert any given number to its binary form
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
#accept a number, and return its binary form | |
x = float(raw_input('Enter a number: ')) | |
isNeg = False | |
if x < 0: | |
x = abs(x) | |
isNeg = True | |
resultInt = '' | |
resultFlt = '' | |
result = '' | |
intPart = int(x) | |
fltPart = x - intPart | |
#print('Integer part: ' + str(intPart)) | |
#print('Float part: ' + str(fltPart)) | |
if x == 0: | |
resultInt = '0' | |
resultFlt = '0' | |
result = resultInt + '.' + resultFlt | |
print(result) | |
p = 0 | |
#convert integer part to binary | |
while intPart > 0: | |
resultInt = str(intPart%2) + resultInt | |
intPart = intPart/2 | |
#print('The binary representation of the int part is: ' + resultInt) | |
#convert float part to binary | |
#we want to find p such that 2^p*x is a whole number | |
while (((2**p) * fltPart)%1 !=0): | |
p +=1 | |
#print ('value of p is: ' + str(p)) | |
#We cast (2^p)*x to an integer | |
num = int((2**p)*fltPart) | |
#print ('num is ' + str(num)) | |
#we now convert this integer to binary | |
while num > 0: | |
resultFlt = str(num%2) + resultFlt | |
num = num/2 | |
#figure out how many zeros are needed to the left of the result | |
for i in range(p - len(resultFlt)): | |
resultFlt = '0' + resultFlt | |
#figure out where to place decimal | |
resultFlt = resultFlt[0:-p] + '.' + resultFlt[-p:] | |
#print ('The binary representation of the float part is: ' + resultFlt) | |
result = resultInt + resultFlt | |
if isNeg: | |
result = '-' + result | |
print('The binary representation of ' + str(x) + ' is : ' + result) | |
else: | |
print('The binary representation of ' + str(x) + ' is : ' + result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment