Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 861
HEMS Avatar asked Mar 26 '26 21:03

HEMS


1 Answers

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))
like image 93
Ignacio Vazquez-Abrams Avatar answered Mar 28 '26 11:03

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!