Last active
December 25, 2015 18:09
-
-
Save boris317/7017950 to your computer and use it in GitHub Desktop.
Encode base 10 integer into other bases
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 BaseConverter(object): | |
| """ | |
| Class for encoding/decoding base 10 values to/from another base | |
| """ | |
| def __init__(self, base, base_digits): | |
| """ | |
| :param base: (int) the base (e.g 2, 16, 64) | |
| :param base_digits: (iterator) of base digits (e.g "01" for base 2, etc) | |
| """ | |
| self.base = base | |
| self.base_digits = base_digits | |
| def encode(self, value): | |
| """ | |
| Take the base 10 ``value`` and encode it to base ``self.base`` | |
| :param value: (int) base 10 integer to be encoded. | |
| :returns: (str) base encoded value. | |
| """ | |
| if value == 0: | |
| return str(self.base_digits[0]) | |
| converted_digits = [] | |
| while value > 0: | |
| converted_digits.append(str(self.base_digits[value % self.base])) | |
| value /= self.base | |
| return "".join(reversed(converted_digits)) | |
| def decode(self, value): | |
| """ | |
| Take the base encoded ``value`` and decode it to base 10 | |
| :param value: (str) base encoded string. | |
| :returns: (int) base 10 decoded integer. | |
| """ | |
| base_10_value = 0 | |
| for i, digit in enumerate(reversed(value)): | |
| base_10_value += self.base_digits.index(digit) * self.base**i | |
| return int(base_10_value) |
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
| # Base 16 | |
| >>> base_16_digits = "0123456789ABCDEF" | |
| >>> c = BaseConverter(16, base_16_digits) | |
| >>> c.encode(30) | |
| '1E' | |
| >>> c.decode('1E') | |
| 30 | |
| # Base 2 (binary) | |
| >>> c = BaseConverter(2, "01") | |
| >>> c.encode(11) | |
| '1011' | |
| >>> c.decode('1011') | |
| 11 | |
| # Base 62 | |
| >>> import string | |
| >>> base_62_digits = "".join([str(n) for n in range(10)]) + string.letters | |
| >>> c = BaseConverter(62, base_62_digits) | |
| >>> c.encode(1002312) | |
| '4cKk' | |
| >>> c.decode('4cKk') | |
| 1002312 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment