二进制转十进制 For 循环

Binary to Decimal For Loop

您好,我是一名新程序员,我正在尝试完成一项作业,这需要我将二进制数转换为二进制数。我没有收到任何错误,但是我没有得到正确的 denary 等价物,请帮忙。这是我到目前为止所做的。

binary = "10111"
denary = 0
length=len(binary)
for i in range(length-1,-1,-1):
   if binary[i] == "1":
    denary += (2**i)
else:
    denary += 0
print(denary)

输出为:

29

你来错方向了。您可以使用 binary[::-1]reversed(binary) 来反转数组。

binary = "10111"
denary = 0

for i, d in enumerate(reversed(binary)):
    if d == "1":
        denary += (2**i)

print(denary)

另请注意,您可以这样做:

denary = int(binary, 2)  # Parses string on base 2 to integer base 10

print(denary)

您可以像这样使用反向列表:

binary = "10111" # needs to be reversed so the lowest bit is in front for ease of computing
denary = 0

# ind = index,  bit = the bitvalue as string of the reversed string 
for ind, bit in enumerate(binary[::-1]): # reversed copy of string
    denary += int(bit)*2**ind  # if bit is 0 this evaluates to 0, else to the  power of 2
print(denary)