Python 将二进制转换为十进制整数输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21765779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:34:01  来源:igfitidea点击:

Converting binary to decimal integer output

pythonpython-2.7binaryintegerbase-conversion

提问by purlinka

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 25back. 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.

我需要走相反的方向。我的教授说,当他检查我们的代码时,他要输入11001,他应该25回来。我查看了我们的笔记,但我不知道如何做到这一点。谷歌和其他互联网资源也没有太大帮助。

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.

最大的问题是我们不允许使用内置函数。我理解为什么我们不允许使用它们,但它使这个问题变得更加困难,因为我知道 Python 有一个内置的二进制到十进制函数。

回答by purlinka

You can use intand set the base to 2(for binary):

您可以使用int并将基数设置为2(对于二进制):

>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>


However, if you cannot use intlike that, then you could always do this:

但是,如果您不能那样使用int,那么您始终可以这样做:

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
>>>

回答by jonrsharpe

If you want/need to do it without int:

如果您想/需要在没有int

sum(int(c) * (2 ** i) for i, c in enumerate(s[::-1]))

This reverses the string (s[::-1]), gets each character cand its index i(for i, c in enumerate(), multiplies the integer of the character (int(c)) by two to the power of the index (2 ** i) then adds them all together (sum()).

这将字符串 ( s[::-1])反转,获取每个字符c及其索引i( for i, c in enumerate(),将字符 ( int(c))的整数乘以2 的索引 ( 2 ** i)次方,然后将它们全部加在一起 ​​( sum())。

回答by MrSheng

I started working on this problem a long time ago, trying to write my own binary to decimal converter function. I don't actually know how to convert decimal to binary though! I just revisited it today and figured it out and this is what I came up with. I'm not sure if this is what you need, but here it is:

我很久以前就开始研究这个问题,试图编写自己的二进制到十进制转换器函数。我实际上不知道如何将十进制转换为二进制!我今天刚刚重新审视它并弄清楚了,这就是我想出的。我不确定这是否是您需要的,但它是:

def __degree(number):
    power = 1

    while number % (10**power) != number:
        power += 1

    return power

def __getDigits(number):
    digits = []
    degree = __degree(number)

    for x in range(0, degree):
        digits.append(int(((number % (10**(degree-x))) - (number % (10**(degree-x-1)))) / (10**(degree-x-1))))
    return digits

def binaryToDecimal(number):
    list = __getDigits(number)
    decimalValue = 0
    for x in range(0, len(list)):
        if (list[x] is 1):
            decimalValue += 2**(len(list) - x - 1)
    return decimalValue

Again, I'm still learning Python just on my own, hopefully this helps. The first function determines how many digits there are, the second function actually figures out they are and returns them in a list, and the third function is the only one you actually need to call, and it calculates the decimal value. If your teacher actually wanted you to write your own converter, this works, I haven't tested it with every number, but it seems to work perfectly! I'm sure you'll all find the bugs for me! So anyway, I just called it like:

同样,我仍然在自己学习 Python,希望这会有所帮助。第一个函数确定有多少个数字,第二个函数实际计算它们并在列表中返回它们,第三个函数是您实际需要调用的唯一一个,它计算十进制值。如果你的老师真的想让你编写自己的转换器,这行得通,我没有用每个数字都测试过,但它似乎完美地工作!我相信你们都会为我找到错误!所以无论如何,我只是这样称呼它:

binaryNum = int(input("Enter a binary number: "))

print(binaryToDecimal(binaryNum))

This prints out the correct result. Cheers!

这将打印出正确的结果。干杯!

回答by M. kavin babu

The input may be string or integer.

输入可以是字符串或整数。

num = 1000  #or num = '1000'  
sum(map(lambda x: x[1]*(2**x[0]), enumerate(map(int, str(num))[::-1])))

# 8

回答by Papi Harpy

This is the full thing

这是完整的东西

binary = input('enter a number: ')
decimal = 0
for digit in binary:
decimal= decimal*2 + int(digit)

print (decimal)

回答by V. Gokul

a = input('Enter a binary number : ')
ar = [int(i) for  i in a]
ar  = ar[::-1]
res = []
for i in range(len(ar)):
    res.append(ar[i]*(2**i))
sum_res = sum(res)      
print('Decimal Number is : ',sum_res)

回答by Théo T. Carranza

Try this solution:

试试这个解决方案:

def binary_int_to_decimal(binary):
    n = 0
    for d in binary:
        n = n * 2 + d

    return n

回答by cegprakash

Binary to Decimal

二进制转十进制

int(binaryString, 2)

Decimal to Binary

十进制转二进制

format(decimal ,"b")