二进制到十进制循环

时间:2018-02-12 22:41:14

标签: python python-3.x bin

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

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

2 个答案:

答案 0 :(得分:4)

你来自错误的方向。您可以使用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)

答案 1 :(得分:2)

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

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)