Created
July 24, 2013 12:16
-
-
Save ernado/6070000 to your computer and use it in GitHub Desktop.
baseN encode
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
import string | |
def baseEncode(number, base=0): | |
if isinstance(number, str): | |
number = long(number) | |
if not isinstance(number, (int, long)): | |
raise TypeError('number must be an integer') | |
if number < 0: | |
raise ValueError('number must be positive') | |
if base < 0: | |
raise ValueError('base must be positive') | |
alphabet = string.digits + string.ascii_letters + '_' | |
if base == 0: | |
base = len(alphabet) | |
baseN = '' | |
while number: | |
number, i = divmod(number, base) | |
baseN = alphabet[i] + baseN | |
return baseN or alphabet[0] | |
if __name__ == '__main__': | |
print baseEncode(12311231231234345365464) # 39pBAwzAwRVux | |
print baseEncode(101) # 1C | |
print baseEncode('12311231231234345365464') # 39pBAwzAwRVux |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment