Created
March 30, 2012 06:12
-
-
Save mursts/2247355 to your computer and use it in GitHub Desktop.
Flickrの短縮URLを作成
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding:utf-8 -*- | |
import sys | |
import re | |
class Base58: | |
def __init__(self): | |
self._CHARS = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' | |
self._CHAR_NUM = len(self._CHARS) | |
def _is_numeric(self, num): | |
matcher = re.compile(r'^[\d]*$') | |
return matcher.match(num) | |
def encode(self, value): | |
if self._is_numeric(value) is None: | |
return '' | |
encoded = '' | |
value = int(value) | |
while value >= self._CHAR_NUM: | |
div, mod = divmod(value, self._CHAR_NUM) | |
encoded = self._CHARS[mod] + encoded | |
value = div | |
return self._CHARS[value] + encoded | |
def decode(self, value): | |
decoded = 0 | |
multi = 1 | |
if value == '': | |
return '' | |
for v in reversed(value): | |
decoded += multi * self._CHARS.index(v) | |
multi *= self._CHAR_NUM | |
return decoded | |
if __name__ == '__main__': | |
args = sys.argv | |
if len(args) < 2: | |
print 'Usage: python {0} value'.format(args[0]) | |
sys.exit() | |
print 'before:{0}'.format(args[1]) | |
b58 = Base58() | |
encoded = b58.encode(args[1]) | |
print 'encoded:{0}'.format(encoded) | |
print 'decoded:{0}'.format(b58.decode(encoded)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment