binary to decimal conversion

Bob Boyken rboyken at hoosier.net
Sun Mar 19 04:55:57 CET 2000


In article <38D3EFF7.2D30C814 at webamused.com>, Joshua Macy <amused at webamused.com> wrote:
> Michael Esveldt wrote:
>> 
>> This morning I wrote a function that takes a binary number as a string
>> and converts it to an integer. There must be a way to optimize this
>> function, anyone have some tips?
>> 
>> def btoi(num):
>>     output = 0
>>     col = range(len(num))
>>     col.reverse()
>>     for bit in range(len(num)):
>>         output = output + pow(2,col[bit])*int(num[bit])
>>     return output
>> 
>> Thanks,
>> Michael
>> _______________________________________________________________
>> dante at oz.net - Michael Esveldt - #FightThePower on Openprojects
> 
>   Yes, use string.atoi
> 
>  >>> import string
>  >>> string.atoi("110", 2)
>  6
>  >>> string.atoi("110110", 2)
>  54

Is there an equivalent function to turn an integer into a binary string?  One that 
would give me "110110" if I fed it "54"?  While I'm at it, I also seek a function 
that will count the bits in a binary string.  If these sound like stupid questions, 
cut me some slack-- I've only been programming in Python for 3 days...

Thanks,

Bob

> 
>   Joshua





More information about the Python-list mailing list