Created
October 11, 2012 18:36
-
-
Save phinpho/3874597 to your computer and use it in GitHub Desktop.
Python PhinphoBase
This file contains hidden or 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
class PhinphoBase(object): | |
class PhinphoBaseNumber(object): | |
decimal = None | |
base = None | |
value = None | |
str_field = 'value' | |
def __init__(self, decimal, base, value=None): | |
self.decimal = decimal | |
self.base = base | |
self.value = value | |
def __unicode__(self): | |
return self.__str__(); | |
def __str__(self): | |
if self.str_field == 'value': | |
return str(self.value) | |
else: | |
return str(self.decimal) | |
BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" | |
def __init__(self): | |
pass | |
def encode(self, n, base=None): | |
if base is None: | |
base = len(self.BASE) | |
def __convert(num, base): | |
if num < base: | |
return "%c" % str(self.BASE[num]) | |
i = num/base | |
j = num%base | |
if i >= base: | |
return "%c%s" % (self.BASE[j], __convert(i, base)) | |
else: | |
return "%c%c" % (self.BASE[j], self.BASE[i]) | |
return self.PhinphoBaseNumber(n, base, __convert(n, base)) | |
def decode(self, n, base=None): | |
if base is None: | |
base = len(self.BASE) | |
i = 0 | |
num = 0 | |
for j in n: | |
num += self.BASE.index(j) * base**i | |
i = i + 1 | |
a = self.PhinphoBaseNumber(num, base, n) | |
a.str_field = 'decimal' | |
return a | |
if __name__ == '__main__': | |
a = PhinphoBase() | |
print a.encode(255,16) | |
print a.decode('phinpho') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment