base converter

Omni Permeable om at nikocity.de
Thu Jun 14 17:26:18 EDT 2001


"Alex Martelli" <aleaxit at yahoo.com> wrote in message news:<9ga0q902gl7 at enews1.newsguy.com>...
> "Greg Jorgensen" <gregj at pobox.com> wrote in message
> news:GE_V6.166783$p33.3516294 at news1.sttls1.wa.home.com...
> >
> > "Fredrik Lundh" <fredrik at pythonware.com> wrote:
> >
> > > def BaseConvert(x, b):
> > >     out = ""
> > >     while x:
> > >         x, d = divmod(x, b)
> > >         out = str(d) + out
> > >     return out
> > >
> >
> > Slightly modified to work with bases > 10:
> >
> > def BaseConvert(x, b):
> >     "convert decimal number x to base b"
> >     digits = "0123456789ABCDEF"
> >     out = ""
> >     if b <= len(digits):
> >         while x:
> >             x, d = divmod(x, b)
> >             out = digits[d] + out
> >     return out
> 
> In general, I think it's better to avoid building a
> string by a loop concatenating single characters.  It
> may not matter much in this case, but...
> 
> def BaseConvert(x, b):
>     import string
>     digits = string.digits + string.uppercase
>     if b>len(digits):
>         raise ValueError, "base %s too large"%b
>     if x == 0:
>         return '0'
>     elif x<0:
>         negative = 1
>         x = -x
>     else:
>         negative = 0
>     result = []
>     while x:
>         x, d = divmod(x, b)
>         result.append(digits[d])
>     if negative:
>         result.append('-')
>     result.reverse()
>     return ''.join(result)
> 
> I've also tried to fix the bug which (I believe)
> would make this loop endlessly for x<0, &c.

tracking down bug#2 : b==1 iterates forever! because : divmod (5,1) == (5,0)

any more elegant solution than this one : 

     elif b==1:
       return '0'*x

unfortunately this throws an exception if x is very large (at least on my machine)



More information about the Python-list mailing list