[Tutor] bin to dec conversion puzzlement

Jim Mooney cybervigilante at gmail.com
Mon Apr 20 09:44:12 CEST 2015


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


More information about the Tutor mailing list