base converter
Alex Martelli
aleaxit at yahoo.com
Thu Jun 14 05:40:14 EDT 2001
"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.
Alex
More information about the Python-list
mailing list