Decimal vs Binary
The decimal numeral system in which numbers are expressed in scales of 10. Whereas the binary numeral system involves expressing numbers in scales of 2.Procedure
Step 1: The whole number part(59) of 59.65625 is divided by 2 until the quotient is 1. The remainder(carry) that is accumulated(either 1 or 0) till the last sequence of operation that gives the quotient 1 is taken in the reverse order of creation, so as to obtain 111011.
59/2 = 29 (1 is taken as carry)
29/2 = 14 (1 is taken as carry)
14/2 = 7 (0 is taken as carry)
7/2 = 3 (1 is taken as carry)
3/2 = 1 (1 is taken as carry)
So when we reverse the carry, we get 11011. Finally, we place the final quotient at the very beginning of the 11011 to get 111011.
Step 2: The decimal part is multiplied by 2 as many times as the number of decimal places in the final result required. To elaborate, let's take the above mentioned example of 59.65625. Here 0.65625 = 65625 * 10^-5.
0.656252 = 1.31250 (1 is taken as carry)
0.312502 = 0.62500 (0 is taken as carry)
0.625002 = 1.25000 (1 is taken as carry)
0.250002 = 0.50000 (0 is taken as carry)
0.50000*2 = 1.00000 (1 is taken as carry)
When we bring the calculations together, we obtain 111011.10101
When we bring the calculations together, we obtain 111011.10101
Source Code
def dec2bin(num):
""""
Function to convert a floating point decimal number to binary number
"""
global wholeList
global decList
whole, dec = str(num).split('.')
whole = int(whole)
dec = int(dec)
counter = 1
while (whole / 2 >= 1):
i = int(whole % 2)
wholeList.append(i)
whole /= 2
decproduct = dec
while (counter <= places):
decproduct = decproduct * (10**-(len(str(decproduct))))
decproduct *= 2
decwhole, decdec = str(decproduct).split('.')
decwhole = int(decwhole)
decdec = int(decdec)
decList.append(decwhole)
decproduct = decdec
counter += 1
wholeList = []
decList = []
try:
num = float(input('Enter a floating point decimal number: '))
except(ValueError):
print('Please enter a valid floating point decimal')
try:
places = int(input('Enter the number of decimal places in the result: '))
dec2bin(num)
if(len(wholeList) > 1):
wholeList.reverse()
wholeList.insert(0, 1)
aster = '*'
print(aster * 60)
print('The binary number of {0} is:' .format(num))
print(*wholeList, end =' ')
print('.', end = ' ')
print(*decList)
print(aster * 60)
except(ValueError):
print('Please enter a valid integer number for places')
Output
Watch this space for more updates. Happy Coding!!!
Comments
Post a Comment