Python Base62 Sample Code
Explore how to encode and decode data using Base62 in Python with clear, easy-to-follow examples.
class Base62:
CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
@staticmethod
def encode(input):
bytes_input = input.encode('utf-8')
result = []
value = 0
bits = 0
for byte in bytes_input:
value = (value << 8) | byte
bits += 8
while bits >= 6:
result.append(Base62.CHARSET[(value >> (bits - 6)) & 0x3F])
bits -= 6
if bits > 0:
result.append(Base62.CHARSET[(value << (6 - bits)) & 0x3F])
return ''.join(result)
@staticmethod
def decode(base62_str):
value = 0
bits = 0
bytes_output = []
for char in base62_str:
value = (value << 6) | Base62.CHARSET.index(char)
bits += 6
if bits >= 8:
bytes_output.append((value >> (bits - 8)) & 0xFF)
bits -= 8
return bytes(bytes_output).decode('utf-8')
# Usage
input_str = "Hello, World!"
encoded = Base62.encode(input_str)
print(f"Encoded: {encoded}")
decoded = Base62.decode(encoded)
print(f"Decoded: {decoded}")