Last active
August 29, 2015 14:26
-
-
Save Ginhing/9ffd03f9b12fc88e63c5 to your computer and use it in GitHub Desktop.
10进制 to 2-36进制
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 NumberBaseConverter(object): | |
def __init__(self, base=10): | |
if not (2 <= base <= 36): | |
raise | |
self.base = base | |
def _remainder_map(self, remainder): | |
if remainder < 10: | |
return str(remainder) | |
else: | |
offset = remainder - 10 | |
return chr(ord('a') + offset) | |
def convert(self, num): | |
mod_result = [] | |
current_num = num | |
while current_num > 0: | |
current_num, remainder = divmod(current_num, self.base) | |
mod_result.append(remainder) | |
return ''.join(reversed([self._remainder_map(i) for i in mod_result])) | |
def __repr__(self): | |
return '<NumberBaseConverter : %d base>' % self.base | |
print(NumberBaseConverter(36).convert(60466175)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment