binary to decimal conversion
Moshe Zadka
moshez at math.huji.ac.il
Sat Mar 18 23:35:16 CET 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()
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
More information about the Python-list
mailing list