Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (16.4k points)
edited by
Hello, all. I can able to solve how to convert a decimal to a binary number. But, If you ask me to convert binary number to decimal, I will just say I don't know how to do it. Is there any way of solving this question without using built-in functions?

Thanks in advance.

1 Answer

0 votes
by (26.4k points)

Try to use int & set the base as 2 (In case of binary):

>>> binary = raw_input('enter a number: ')

enter a number: 11001

>>> int(binary, 2)

25

>>>

If you don't want to use int, try:

binary = raw_input('enter a number: ')

decimal = 0

for digit in binary:

    decimal = decimal*2 + int(digit)

print decimal

Look at the demonstration:

>>> binary = raw_input('enter a number: ')

enter a number: 11001

>>> decimal = 0

>>> for digit in binary:

...     decimal = decimal*2 + int(digit)

...

>>> print decimal

25

>>>

Are you interested to learn the topics of Python in detail? You can join our Python certification course and get certified. 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+3 votes
2 answers
0 votes
1 answer
asked Oct 15, 2019 in Python by Sammy (47.6k points)

Browse Categories

...