binary to decimal conversion

Michal Bozon bozon at natur.cuni.cz
Tue Mar 21 09:16:43 EST 2000


On 18 Mar 2000, 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
# - - - - - -
def btoi(num, o="0", i="1"):
    def powL(a, e): # can handle BIG numbers (long)
        import sys
        mi = sys.maxint # maximal value of integer. Higher must be long.
        r = 1L
        for i in range(e):
            r = r*a
        if r < mi: return int(r)
        return r
    c = [o, i]
    output = 0  
    for i in range(len(num)):
        output = output+c.index(num[-i-1])*powL(2, i)
# - - - - - -
Without warranty. Reproduced from my brain. (I wrote this func before
a week. This func should handle VERY large strings which yield long
numbers. If the strings conains binary string using other characters e.g.
s = "IOOOIOIOIOOOIOI", you simply use: btoi(s, "O", "I")

regards, 
Michal Bozon
Fac.Sci., Chrales Univ., Prague, Czech Rep.
bozon at natur.cuni.cz
     


> 
> Thanks,
> Michael
> _______________________________________________________________
> dante at oz.net - Michael Esveldt - #FightThePower on Openprojects
> 
> 




More information about the Python-list mailing list