I can't seem to get my head around this 'simple' book example of
binary-to-decimal conversion, which goes from left to right:

B = '11011101'
I = 0
while B:
    I = I * 2 + int(B[0])
    B = B[1:]

print(I)
>>> 221

My thought was to go from right to left, multiplying digits by successive
powers of two, and adding, like so:

B = '11011101'
sum = 0

for exp, num in enumerate(reversed(B)):
    sum += int(num) * 2**exp

print(sum)
>> 221

Both methods work but I just can't see how the first one does. Am I missing
something obvious here?

-- 
Jim
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to