[Tutor] bin to dec conversion puzzlement

Dave Angel davea at davea.name
Tue Apr 21 01:43:51 CEST 2015


On 04/20/2015 04:15 PM, Jim Mooney wrote:
>   The key is that the result gets multiplied by 2 each time
>
>> so for an N bit number the leftmost digit winds up being
>> effectively 2**N, which is what you want.
>>
>
>
>> Alan G
>
>
> Ah, the light dawns once it was restated. It would be even simpler if you
> could multiply each element of the binary number by it's respective power
> of two, and sum them all at once. I hear Py 3.5 will have vector abilities.
> I wonder it if would do something like that.

It's important to understand these conversion methods, or I would have 
earlier mentioned that you can convert from a binary string simply by

     x = int("1011", 2)

No loop needed.


But if you need a loop for an analagous algorithm, find a way to either 
minimize the number of times through the loop, or to reduce the work 
done in each loop.

Ben's algorithm is much simpler than the one in the book you're reading.

     binary_text = '11011101'
     result = 0

     for binary_digit in binary_text:
         # Accumulate powers of 2 for each digit.
         result = result * 2 + int(binary_digit)

     print(result)

But more importantly, it's much simpler than calculating various powers 
of two and multiplying the various coefficients by them, and somehow 
"sum them all at once".


-- 
DaveA


More information about the Tutor mailing list