将二进制转换为十进制整数输出 [英] Converting binary to decimal integer output
问题描述
我需要将二进制输入转换为十进制整数.我知道如何从十进制转换为二进制:
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)
我需要朝相反的方向走.我的教授说,当他检查我们的代码时,他将输入 11001
,他应该会得到 25
.我已经仔细阅读了笔记,但不知道该怎么做.Google和其他互联网资源也没有太大帮助.
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.
最大的问题是我们不允许使用内置函数.我知道为什么我们不允许使用它们,但是这使这个问题变得更加困难,因为我知道Python有一个内置的二进制到十进制函数.
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.
推荐答案
您可以使用 int
并将基数设置为 2
(对于二进制):
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
>>>
但是,如果您不能像这样使用 int
,那么您始终可以这样做:
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
下面是一个演示:
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
... decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>
这篇关于将二进制转换为十进制整数输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!