Error converting binary to integer when the last bit is zero [low]

I am using the manual method to convert binary to decimal. This code works fine when the last bit is high, for example: 1001. The error occurs when the last bit is zero [low]. For example, 1010 should give 10, but it gives 5 because the last bit is not considered. Can anyone help me with this.

x=raw_input('Enter the binary value:')
x=[int(xi) for xi in x]

for i in range(0,len(x)):

print sum



source to share

3 answers

You are misinterpreting the problem. The problem is not that it ignores the last bit if it is 0, the problem is that it reads the binary sequence backwards. When you download "1010", it treats it as "0101".

sum = sum + x[i] * (pow(2, len(x) - i - 1))




The following code works:

x = raw_input('Enter the binary value:')
x = [int(i) for i in x]

s = sum(2**i for i,j in enumerate(x[::-1]) if j==1)



This code changes the input so that when we parse it bit by bit (pun intended), it raises 2 to the index of that bit if that bit is 1. Also, don't use it sum

as a variable name. This is a built-in function.



I think the simplest way to look at this is:

x = '1010'

_sum = 0
for i in x: # go over every digit from left to right
    _sum = (_sum + int(i)) * 2
_sum /= 2  # when exiting the loop - we multiplied one extra time - fix it!

print _sum # prints 10




All Articles