thoslin
thoslin

Reputation: 7019

Python short url generator

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.

Upvotes: 0

Views: 1089

Answers (1)

Karl Knechtel
Karl Knechtel

Reputation: 61526

Looking at the whole code: The net effect of encode() is to apply _encode() to the least-significant self.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.

Upvotes: 0

Related Questions