short url的一个python实现
import hashlibdef shorturl(url): base32 = ['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', '0', '1', '2', '3', '4', '5'] m = hashlib.md5() m.update(url) hexStr = m.hexdigest() hexStrLen = len(hexStr) subHexLen = hexStrLen / 8 output = [] for i in range(0,subHexLen): subHex = '0x'+hexStr[i*8:(i+1)*8] res = 0x3FFFFFFF & int(subHex,16) out = '' for j in range(6): val = 0x0000001F & res out += (base32[val]) res = res >> 5 output.append(out) return output