Commits

Miki Tebeka committed 4b805d6

initial import

  • Participants

Comments (0)

Files changed (6)

+syntax: glob
+
+README.html
+include test_base62.py
+include README.md
+base62 encoder decoder.
+
+For more info see [https://bitbucket.org/tebeka/base62-py](https://bitbucket.org/tebeka/base62-py)
+'''Encode/decode numbers from/to base62.'''
+
+__version__ = '0.1.0'
+
+import string
+
+chars = string.digits + string.letters
+base = len(chars)
+
+
+def encode(num):
+    '''Encode number in base62, returns a string.'''
+    if num < 0:
+        raise ValueError('cannot encode negative numbers')
+
+    if num == 0:
+        return chars[0]
+
+    digits = []
+    while num:
+        rem = num % base
+        num = num // base
+        digits.append(chars[rem])
+    return ''.join(reversed(digits))
+
+
+def decode1(string):
+    '''Decode a base62 string to a number.'''
+    strlen = len(string)
+    num = 0
+
+    idx = 0
+    for char in string:
+        power = (strlen - (idx + 1))
+        num += chars.index(char) * (base ** power)
+        idx += 1
+
+    return num
+
+
+def decode(string):
+    '''Decode a base62 string to a number.'''
+    loc = chars.index
+    size = len(string)
+    num = 0
+
+    for i, ch in enumerate(string, 1):
+        num += loc(ch) * (base ** (size - i))
+
+    return num
+import base62
+
+from setuptools import setup
+
+setup(
+    name='base62',
+    version=base62.__version__,
+    py_modules=['base62'],
+    entry_points={
+        'console_scripts': [
+            'base62 = base62:main',
+        ]
+    },
+    test_suite = 'nose.collector',
+)
+import base62
+
+
+def check(n, b62):
+    assert base62.encode(n) == b62, 'bad encode'
+    assert base62.decode1(b62) == n, 'bad decode'
+
+
+test_cases = [
+    (0, '0'),
+    (10, 'a'),
+    (630, 'aa'),
+    (1097900471, '1ciG47'),
+]
+
+
+def test_base62():
+    for n, b62 in test_cases:
+        yield check, n, b62