Last active
August 22, 2018 06:17
-
-
Save travishen/1135335b76dc4b25c8b95ba771aa9f96 to your computer and use it in GitHub Desktop.
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 BaseChanger: | |
BASE = 10 | |
NEW_BASE = None | |
MINUS_SIGN = False | |
def __init__(self, n, new_base, n_base=BASE): | |
self.NEW_BASE = new_base | |
if n_base: | |
self.BASE = n_base | |
if new_base < 2 or new_base > 36: | |
raise NotImplementError('New base number must between 2 and 36') | |
self.n = int(str(n), base=n_base) | |
if self.n < 0: | |
self.MINUS_SIGN = True | |
self.n = self.n * -1 | |
self.digitalize() | |
def digitalize(self): | |
self.digits = [] | |
if self.n == 0 or self.n < self.NEW_BASE: | |
self.digits = [0] | |
else: | |
n = self.n | |
b = self.NEW_BASE | |
while n >= b: | |
# mod = n % b | |
# div = n // b | |
div, mod = divmod(n, b) | |
self.digits.insert(0, mod) | |
n = div | |
self.digits.insert(0, n) | |
return self.digits | |
@staticmethod | |
def encode(digits): | |
map_str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' | |
return ''.join(map_str[c] for c in digits) | |
@property | |
def encoding(self): | |
s = self.encode(self.digits) | |
if self.MINUS_SIGN: | |
return '-' + s | |
return s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment