Created
March 30, 2018 06:46
-
-
Save ankanch/2a9a7d305d1ba5079aa17338f7c50d39 to your computer and use it in GitHub Desktop.
USED FOR SHORT URL SERVICE - 10 base and 62 base number conversion
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
# USED FOR SHORT URL SERVICE | |
# 10 base number and 62 based number convertion | |
# used for 62 based code convert to primary key in database | |
# only number large than and equal to 0 works | |
# | |
# by Kanch -> kanch is me @ gmail . com | |
# http://akakanch.com | |
# | |
from math import pow | |
base62 = [ "0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z" ] | |
def swap1062(val): | |
# covert 10 base to 62 base | |
bits = [] | |
while val/62 > 0: | |
bi = val%62 | |
val//=62 | |
bits.append(bi) | |
bits.append(val) # value it's now from lower bits to higher | |
#print(bits) | |
return "".join([ base62[x] for x in bits ]) | |
def swap6210(val): | |
# convert 62 base to 10 base | |
bits = [ base62.index(x) for x in val ] | |
pk = [ int(x*pow(62,bits.index(x))) for x in bits ] | |
return sum(pk) | |
if __name__ == "__main__": | |
print("test for swap1062():") | |
print("\t" + swap1062(44354)) | |
print("\t" + swap1062(0)) | |
print("\t" + swap1062(443542342123)) | |
print("test for swap6210():") | |
print("\t" + str(swap6210("oxb0")) + "\t\treal=oxb0") | |
print("\t" + str(swap6210("VTs49O70")) + "\t\treal=443542342123") | |
print("\t" + str(swap6210("0")) + "\t\treal=0") | |
for i in range(100000): # less than 1 sec to process | |
swap1062(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment