Last active
August 29, 2015 13:56
-
-
Save eduardo-matos/8813008 to your computer and use it in GitHub Desktop.
Conversão de bases em Python
This file contains hidden or 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
| 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