[Tutor] Function for converting ints from base10 to base2?

David Perlman dperlman at wisc.edu
Wed Feb 21 06:04:37 CET 2007


I suspect the function I sent out earlier, using octal conversion and  
a lookup table, will be faster.  But it would be very interesting to  
see some simple benchmarks.

On Feb 20, 2007, at 10:47 PM, Dick Moores wrote:

> I was surprised to be unable to find a function in Python for
> converting ints from base10 to base2. Is there one?
>
> I wrote one, but have I reinvented the wheel again? (Even if I have,
> it was an interesting exercise for me.)
>
> I know some of you CS people won't like what I do with negative ints,
> but I wanted it this way. On other points than that, I'd appreciate
> criticism/suggestions.
>
> ===========================================================
> def computeBin(n):
>      """converts base10 integer n to base2 b as string"""
>      from math import log, floor
>      sign = ''
>      if n == 0:
>          b = '0'
>      else:
>          if n < 0:
>              sign = "-"
>              n = -n
>          e = int(floor(log(n,2)))
>          b = '1'
>
>          for x in range(e):
>              r = n % 2**e
>              if r >= 2**(e-1):
>                  b += '1'
>              else:
>                  b += '0'
>              e -= 1
>      return sign + b
>
> def printResult(n,b):
>      print "%d is %s" % (n, b)
>
> def confirmResult(n,b):
>      print "Confirming using int():"
>      print "int(%s,2) is %s" % (b, int(b,2))
>
> if __name__ == '__main__':
>      n = 1234567890
>      b = computeBin(n)
>      printResult(n,b)
>      confirmResult(n,b)
> ==============================================
>
> Dick Moores
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama





More information about the Tutor mailing list