Python 短网址生成器
我正在使用此代码生成短网址。 http://code.activestate.com/recipes/576918/
这个想法是编码使用 base62 和函数 enbase 的整数 id 工作正常。
class UrlEncoder(object):
...
def enbase(self, x, min_length=0):
result = self._enbase(x)
padding = self.alphabet[0] * (min_length - len(result))
return '%s%s' % (padding, result)
但我不太明白这段代码的用途:
class UrlEncoder(object):
...
def encode_url(self, n, min_length=0):
return self.enbase(self.encode(n), min_length)
def decode_url(self, n):
return self.decode(self.debase(n))
def encode(self, n):
return (n & ~self.mask) | self._encode(n & self.mask)
为什么先编码然后enbase?这个按位运算有什么作用? 有人能给我一些启发吗?谢谢。
I'm using this code to generate short url. http://code.activestate.com/recipes/576918/
The idea is to encode an integer id using base62 and function enbase just works fine.
class UrlEncoder(object):
...
def enbase(self, x, min_length=0):
result = self._enbase(x)
padding = self.alphabet[0] * (min_length - len(result))
return '%s%s' % (padding, result)
But I don't quite understand what this code is for:
class UrlEncoder(object):
...
def encode_url(self, n, min_length=0):
return self.enbase(self.encode(n), min_length)
def decode_url(self, n):
return self.decode(self.debase(n))
def encode(self, n):
return (n & ~self.mask) | self._encode(n & self.mask)
Why encode then enbase? What does that bitwise operation do?
Could someone shed some light on me? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看整个代码:
encode()
的最终效果是将_encode()
应用于最低有效的self.block_size
-many值的位。_encode()
似乎反转了这些位。这似乎只是一些额外的混乱。代码下面的文档解释了为什么他们要进行所有这些额外的洗牌。Looking at the whole code: The net effect of
encode()
is to apply_encode()
to the least-significantself.block_size
-many bits of the value._encode()
appears to reverse those bits. It seems to be just a bit of additional scrambling. The documentation below the code explains why they are doing all these extra shuffles.