Python Base Converter
Python-baseconv is a lightweight Python module designed to convert numbers from base 10 integers to base X strings and vice versa. It provides predefined converters for common bases like binary, hexadecimal, and Base64, as well as the ability to define custom alphabets. The current version is 1.2.2, with its last release in April 2019, suggesting a maintenance-focused release cadence.
Warnings
- gotcha The library was originally developed with Python 2.7 in mind, as evidenced by Python 2.7 classifiers on PyPI and use of 'L' suffix for long integers in older examples. While the core functionality generally works in Python 3, active Python 3-specific maintenance might be limited.
- deprecated Do not confuse `python-baseconv` with `django.utils.baseconv`. The latter was a private, undocumented module within Django that borrowed code from `python-baseconv` but has been deprecated in Django 4.0 and completely removed in Django 5.0. Directly importing `django.utils.baseconv` will fail in modern Django versions.
- gotcha The `BaseConverter` class and its methods (`encode`, `decode`) will raise `ValueError` for invalid inputs, such as an empty digit alphabet during instantiation, using a sign character within the digit alphabet, or encountering digits during decoding that are not present in the converter's alphabet.
Install
-
pip install python-baseconv
Imports
- base2, base16, base36, base56, base58, base62, base64
from baseconv import base2, base16, base36, base56, base58, base62, base64
- BaseConverter
from baseconv import BaseConverter
Quickstart
from baseconv import base62, BaseConverter
# Using a predefined converter (e.g., Base62)
encoded_value = base62.encode(1234567890)
print(f"Encoded to Base62: {encoded_value}")
decoded_value = base62.decode(encoded_value)
print(f"Decoded from Base62: {decoded_value}")
# Creating a custom converter
my_alphabet = '0123456789ABCDEF'
my_hex_converter = BaseConverter(my_alphabet)
custom_encoded = my_hex_converter.encode(255)
print(f"Custom Hex Encoded: {custom_encoded}")
custom_decoded = my_hex_converter.decode(custom_encoded)
print(f"Custom Hex Decoded: {custom_decoded}")