Last active
July 12, 2018 08:47
-
-
Save cyingfan/773da3a27f9ceca3febbbfc381c9be77 to your computer and use it in GitHub Desktop.
Base converter
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
from collections import OrderedDict | |
class BaseConv: | |
def __init__(self, charset:str): | |
self.charset = OrderedDict.fromkeys(charset) | |
i = 0 | |
for k in self.charset: | |
self.charset[k] = i | |
i += 1 | |
self.charset_string = ''.join(self.charset.keys()) | |
self.base_count = len(self.charset) | |
def fromdec(self, num:int) -> str: | |
s = "" | |
while num > 0: | |
index = num % self.base_count | |
s = self.charset_string[index] + s | |
num = (num - index) // self.base_count | |
return s | |
def todec(self, s:str) -> int: | |
sanitized = ''.join(x for x in s if x in self.charset) | |
slen = len(sanitized) | |
num = 0 | |
for i in range(slen): | |
num += self.charset[sanitized[i]] * (self.base_count ** (slen - i - 1)) | |
return num | |
class Coding: | |
def __init__(self, frombase:BaseConv, tobase:BaseConv): | |
self.frombase = frombase | |
self.tobase = tobase | |
def encode(self, fromstr: str) -> str: | |
return self.tobase.fromdec(self.frombase.todec(fromstr)) | |
def decode(self, fromstr: str) -> str: | |
return self.frombase.fromdec(self.tobase.todec(fromstr)) |
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
from BaseConv import BaseConv, Coding | |
b64str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
asciistr = ''.join(chr(i) for i in range(256)) | |
b64 = BaseConv(b64str) | |
ascii = BaseConv(asciistr) | |
s = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure. " | |
c = Coding(ascii, b64) | |
print(c.encode(s)) | |
print(c.decode(c.encode(s))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment