[Tutor] Function for converting ints from base10 to base2?
Dick Moores
rdm at rcblue.com
Wed Feb 21 08:18:04 CET 2007
Well, I can't compare mine with yours (where is it?), but using the
template in timeit.py:
template = """
def inner(_it, _timer):
from decToBin import computeBin
_t0 = _timer()
for _i in _it:
computeBin(12345678901234567890)
_t1 = _timer()
return _t1 - _t0
"""
I get these results:
for computeBin(12345678901234567890)
1000 loops, best of 3: 448 usec per loop
for computeBin(1234567890)
10000 loops, best of 3: 59.7 usec per loop
for computeBin(12345)
10000 loops, best of 3: 35.2 usec per loop
Dick Moores
At 09:04 PM 2/20/2007, David Perlman wrote:
>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
> >
>
>--
>-dave----------------------------------------------------------------
>After all, it is not *that* inexpressible.
>-H.H. The Dalai Lama
More information about the Tutor
mailing list