binary to decimal conversion

Cliff Crawford cjc26 at nospam.cornell.edu
Sat Mar 18 19:22:18 EST 2000


I would do the following:

def btoi(num):
    output = 0
    for bit in range(len(num)):
        output = output << 1
        if num[bit] == '1':
            output = output + 1
    return output

That lets you get rid of the call to reverse(), and all the extra
variables.

* Moshe Zadka menulis:
| 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()
|       current_power = 1
| >     for bit in range(len(num)):
| >         output = output + pow(2,col[bit])*int(num[bit])
| Better:
|           if num[bit] == '1':
|               output = output+current_power
|           current_power = current_power << 1
| 
| Or try some list functions:
| 
| powers = map(pow, [2]*len(num), range(len(num)))
| return reduce(operator.add, map(operator.mult, powers, map(int, num)))
| 
| (You can calculate powers in advance, and just take slices)
| --
| Moshe Zadka <mzadka at geocities.com>. 
| http://www.oreilly.com/news/prescod_0300.html
| http://www.linux.org.il -- we put the penguin in .com
| 
| 


-- 
cliff crawford    -><-    http://www.people.cornell.edu/pages/cjc26/
"IS I yes wardrobe yield [the] evaluation."     member of A.H.M.A.D.



More information about the Python-list mailing list