string.atoi and string.atol broken?
Peter Otten
__peter__ at web.de
Tue Jan 25 19:31:50 EST 2005
Mike Moum wrote:
> s.atoi('4',3) should result in 11
>
> s.atoi('13',4) should result in 31
>
> s.atoi('12',4) should result in 30
>
> s.atoi('8',4) is legitimate, but it generates an error.
>
> Is this a bug, or am I missing something obvious?
You and atoi() seem to disagree about the direction of the conversion, and
atoi() wins :-). It converts a string representation of a number into the
corresponding integer. The second parameter specifies in what base this
string is given.
You seem to want something like
import string
def itoa(n, base):
assert 2 <= base <= 16
if n < 0:
digits = ["-"]
n = -n
else:
digits = []
while n:
n, m = divmod(n, base)
digits.append(string.hexdigits[m])
digits.reverse()
return "".join(digits)
if __name__ == "__main__":
assert itoa(4, 3) == "11"
assert itoa(13, 4) == "31"
assert itoa(12, 4) == "30"
assert itoa(8, 4) == "20"
Peter
More information about the Python-list
mailing list