binary to decimal conversion

Greg Ewing greg at cosc.canterbury.ac.nz
Tue Mar 21 23:17:40 EST 2000


Michal Bozon wrote:
> 
> def btoi(num, o="0", i="1"):
>     def powL(a, e): # can handle BIG numbers (long)
>        ...
>     c = [o, i]
>     output = 0
>     for i in range(len(num)):
>         output = output+c.index(num[-i-1])*powL(2, i)

Calculating 2^n from scratch for each bit is a tad wasteful.
How about

  def btoi(num):
    result = 0L
    bit = 1L
    n = len(num)
    while n:
      n = n - 1
      if num[n] == "1":
        result = result + bit
      bit = bit << 1
    if result <= sys.maxint:
      return int(result)
    else:
      return result
    
-- 
Greg Ewing, Computer Science Dept,
+--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg at cosc.canterbury.ac.nz	   +--------------------------------------+



More information about the Python-list mailing list