Skip to content

Instantly share code, notes, and snippets.

@eduardo-matos
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save eduardo-matos/8813008 to your computer and use it in GitHub Desktop.

Select an option

Save eduardo-matos/8813008 to your computer and use it in GitHub Desktop.
Conversão de bases em Python
from math import floor
BASE62 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
def base_convert(src, from_base=10, to_base=16, alphabet=BASE62):
src = str(src)
from_alphabet = alphabet[:from_base]
to_alphabet = alphabet[:to_base]
# first convert to base 10
val = 0
numlen = len(src)
for i in xrange(numlen):
val = val * from_base + from_alphabet.find(src[i])
if val < 0:
return 0
# then convert to any base
r = val % to_base
res = to_alphabet[r];
q = floor(val / to_base)
while q:
r = q % to_base
q = floor(q / to_base)
res = to_alphabet[int(r)] + res;
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment