Last active
August 29, 2015 14:26
-
-
Save mbarkhau/1b918cb3b4a2bdaf841c to your computer and use it in GitHub Desktop.
Convert between str using arbitrary base and integer (positive integers only)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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