我正在为我的网站制作一个URL缩写程序,我目前的计划(我对建议持开放态度)是使用一个节点ID来生成缩短的URL。因此,理论上,节点26可能是short.com/z
,节点1可能是short.com/a
,节点52可能是short.com/Z
,节点104可能是short.com/ZZ
。当用户访问该URL时,我需要反转这个过程(显然)。
我可以想出一些笨拙的方法来解决这个问题,但我猜还有更好的方法。有什么建议吗?
发布于 2015-06-28 13:03:14
>>> ord("a")
97
>>> chr(97)
'a'
发布于 2017-02-28 08:38:03
如果在一个整数/长整型中绑定了多个字符,就像我的问题一样:
s = '0123456789'
nchars = len(s)
# string to int or long. Type depends on nchars
x = sum(ord(s[byte])<<8*(nchars-byte-1) for byte in range(nchars))
# int or long to string
''.join(chr((x>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))
产生'0123456789'
和x = 227581098929683594426425L
发布于 2010-09-09 11:53:18
对网址进行编码的BASE58呢?比如flickr就是这样。
# note the missing lowercase L and the zero etc.
BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
url = ''
while node_id >= 58:
div, mod = divmod(node_id, 58)
url = BASE58[mod] + url
node_id = int(div)
return 'http://short.com/%s' % BASE58[node_id] + url
把它变成一个数字也没什么大不了的。
https://stackoverflow.com/questions/3673428
复制相似问题