[Tutor] Binary to Decimal conversion

A.T.Hofkamp a.t.hofkamp at tue.nl
Tue Mar 10 17:01:53 CET 2009


Hello,

Chris Castillo wrote:
> Thanks for clearing that up. I knew it was much simpler than I was trying to
> make it I just couldn't quite see the logic that I needed for the problem
> clearly. Thanks for the elegant code.
> 
> On Mon, Mar 9, 2009 at 10:53 PM, Moos Heintzen <iwasroot at gmail.com> wrote:
>>
>> binnum = raw_input("Please enter a binary number:  ")
>> decnum = 0
>> rank = 1
>>
>> for i in reversed(binnum):
>>    decnum += rank * int(i)
>>    rank *= 2

If you reverse the computation, it gets even simpler:


binstr = raw_input("Please enter a binary number:  ")
decnum = 0

for i in binstr:
     decnum = decnum * 2 + int(i)

print decnum




If you want to preserve the binary spirit of the conversion, you should of 
course do

for i in binstr:
     decnum = (decnum << 1) | int(i)

instead.


Sincerely,
Albert


More information about the Tutor mailing list