Skip to content

Instantly share code, notes, and snippets.

@dyjjones
Created August 7, 2016 12:09
Show Gist options
  • Save dyjjones/799e9e6ad2e611b30393e7c2f9836112 to your computer and use it in GitHub Desktop.
Save dyjjones/799e9e6ad2e611b30393e7c2f9836112 to your computer and use it in GitHub Desktop.
base converter
from string import digits, ascii_lowercase
int_to_base_36 = digits + ascii_lowercase
base_36_to_int = {v:k for k,v in enumerate(int_to_base_36)}
def largest_multiple(n, multiplier):
print(type(n), type(multiplier))
exp = 1
while True:
if multiplier**(exp+1) > n:
return exp
else:
exp += 1
def convert_base(n, base_one, base_two):
n = str(n)
# to base 10
if base_one == base_two:
return str(n)
if base_one == 10:
base_10 = int(n)
else:
#if base_one > 10:
base_10 = sum([base_36_to_int[d] * base_one**i for i,d in enumerate(n[::-1])])
#else:
# base_10 = sum([int(d) * base_one**i for i,d in enumerate(n[::-1])])
if base_two == 10:
return base_10
else:
exp = largest_multiple(base_10 ,base_two)
base_two_n = ''
mod = base_10
for i in range(exp, -1, -1):
if i == 0:
base_two_n += int_to_base_36[mod]
else:
div, mod = divmod(mod, base_two**i)
base_two_n += int_to_base_36[div]
return base_two_n
print(convert_base(5214534535, 10, 30))
#print(largest_multiplie(326, 8))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment