Skip to content

Instantly share code, notes, and snippets.

@mbarkhau mbarkhau/int2str.py
Last active Aug 29, 2015

Embed
What would you like to do?
Convert between str using arbitrary base and integer (positive integers only)
DIGITS = (
string.digits +
string.ascii_lowercase +
string.ascii_uppercase +
string.punctuation
)
def int2str_converter(base):
assert 2 <= base <= len(DIGITS)
digits = DIGITS[:base]
def int2str(int_num):
assert int_num >= 0
num_digits = []
while int_num > 0 or not num_digits:
int_num, i = divmod(int_num, len(digits))
num_digits.append(digits[i])
return "".join(reversed(num_digits))
return int2str
def str2int_converter(base):
assert 2 <= base <= len(DIGITS)
digits = DIGITS[:base]
def str2int(str_num):
int_num = 0
o = len(str_num) - 1
for i, digit in enumerate(str_num):
assert digit in digits
int_num += digits.index(digit) * (base ** (o - i))
return int_num
return str2int
i2s2 = int2str_converter(base=2)
i2s8 = int2str_converter(base=8)
i2s16 = int2str_converter(base=16)
i2s36 = int2str_converter(base=36)
i2s62 = int2str_converter(base=62)
i2s94 = int2str_converter(base=94)
s2i2 = str2int_converter(base=2)
s2i8 = str2int_converter(base=8)
s2i16 = str2int_converter(base=16)
s2i36 = str2int_converter(base=36)
s2i62 = str2int_converter(base=62)
s2i94 = str2int_converter(base=94)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.