In: Computer Science
In the decimal system (base 10), a natural number is represented as a sequence dndn−1 . . . d0 of (decimal) digits, each of which is in the range 0..9. The value of the number is d0 ×100 +d1 ×101 +···+ dn ×10n. Similarly, in the binary system (base 2), a natural number is represented as a sequence bnbn−1 · · · b0 of (binary) digits, each of which is 0 or 1. The value of the number is b0 ×20 +b1 ×21 +···+bn ×2n. For example, the value of the number whose binary representation is 101is: 1×20+0×21+1×22 =1+0+4=5.
Without using any built-in functions for converting numbers, write a function that takes as input the binary representation of a positive integer n and returns its decimal representation.
# Python function to take the binary input and return its
decimal notation
#####Function starts here
def convertToDecimal(bina):
n=len(bina)
res=0
for i in range(1,n+1):
res=res+ int(bina[i-1])*2**(n-i)
return res
####Function ends here
## Driver program for the function
binary=[]
binary = input ('Enter binary to be converted: ')
decimal= convertToDecimal(binary)
print("Decimal Equivalanet is ", decimal)
Output Screenshot:
Code: