Python将二进制转换为十进制 [英] Python-Converting binary to decimal
问题描述
我正在执行冲突分配,这使我们创建了一个python程序,无需使用bin()函数或list()即可将二进制转换为十进制.我计划将每个1和0存储在一个函数中,该函数将在以后相乘.但是,我不确定应该怎么做
Im doing a colledge assignment which is have us create a python program to convert binary to decimal without using the bin() function or list(). I'm plan to have each 1's and 0's stored in a function which will be multiplied later. However, I'm not sure how am i suppose to do so
推荐答案
好吧,您可以将二进制数字作为字符串传递,并以相反的顺序对其进行迭代,将每个0或1乘以2 ^ n,其中n为每个循环周期递增一个数字.
Well, you could pass the binary number as a string, and iterate over it in reverse order, multiplying each 0 or 1 by 2^n, where n is a number incremented at each loop cycle.
def bin2dec(b):
number = 0
counter = 0
for i in b[::-1]: # Iterating through b in reverse order
number += int(i)*(2**counter)
counter += 1
return number
bin2dec("101010") # 42
就像Byte Commander一样,您也可以在循环中使用枚举而不是手动计数器,它具有相同的目的.
EDIT : Like Byte Commander did, you could also use enumerate in the loop instead of a manuel counter, it serve the same purpose.
def bin2dec(b):
number = 0
for idx, num in enumerate(b[::-1]): # Iterating through b in reverse order
number += int(num)*(2**idx)
return number
这篇关于Python将二进制转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!