I need to convert a binary input into a decimal integer. I know how to go from a decimal to a binary:
n = int(raw_input('enter a number: '))
print '{0:b}'.format(n)
I need to go in the reverse direction. My professor said that when he checks our code, he is going to input 11001
, and he should get 25
back. I've looked through our notes, and I cannot figure out how to do this. Google and other internet resources haven't been much help either.
The biggest problem is that we are not allowed to use built-in functions. I understand why we are not allowed to use them, but it's making this problem much more difficult, since I know Python has a built-in function for binary to decimal.
You can use int
and set the base to 2
(for binary):
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>
However, if you cannot use int
like that, then you could always do this:
binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print decimal
Below is a 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
>>>