[Tutor] bin to dec conversion puzzlement

Marc Tompkins marc.tompkins at gmail.com
Mon Apr 20 17:21:11 CEST 2015


On Apr 20, 2015 6:56 AM, "Jim Mooney" <cybervigilante at gmail.com> wrote:
>
> 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

Start from 0.
As long as there are any digits left,
a) Multiply by 2, add the leftmost digit.
b) Chop off the leftmost digit.
Lather, rinse, repeat.

It _does_ seem counterintuitive to do it from the left, but it's actually
quite simple.


More information about the Tutor mailing list