Entry
Is there a way to read and write base-n strings using pack or unpack?
Jul 5th, 2000 09:59
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 37, Guido van Rossum
"""
Packages: maths.bases;basic_datatypes.strings
"""
"""
> Is there a way to read and write base-n strings using pack or unpack. i.e.
> if I have a string '1001001011' and I tell it to read a 10-digit binary
> string, it would return 587. If not using pack or unpack, is there another
> way to do it?
Easy:
"""
def getnum(s, base=2):
x = 0
for c in s:
i = ord(c) - ord('0')
assert 0 <= i < base
x = x*base + i
return x
print getnum('1001001011')
# 587