I am using manual method to convert binary to decimal. This code works fine where the last bit is high for eg: 1001. The error arises when the last bit is zero[low]. For eg: 1010 should give 10 but gives 5 because the last bit is not considered.Could any one help me in this.
x=raw_input('Enter the binary value:')
x=[int(xi) for xi in x]
sum=0
for i in range(0,len(x)):
sum=sum+x[i]*(pow(2,i))
print sum
You're misinterpreting the problem. The issue isn't that it's ignoring the last bit if it's 0, the problem is that it's reading the binary sequence backwards. When you feed in "1010", it processes it as "0101".
sum = sum + x[i] * (pow(2, len(x) - i - 1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With