短網址服務需將長整數 ID 轉換為短字串(如 abc123),反之亦然。Base54 編碼排除易混淆字元(0/O、1/I/l、2/Z 等),比 Base62 更適合人工閱讀與輸入。
CODES = "abcdefghjkmnpqrstuvwxyz23456789ABCDEFGHJKMNPQRSTUVWXYZ"
# 長度 54,移除: 0, O, 1, I, l, 2, Z 等易混淆字元
import math
import decimal
def convert_to_code(num):
"""將非負整數轉換為 Base54 字串"""
def get_num(n, out=''):
n = decimal.Decimal(n)
if n > 53:
key = int(n % 54)
n = math.floor(n / 54) - 1
return get_num(n, CODES[key] + out)
else:
return CODES[int(n)] + out
return get_num(num)
def convert_to_num(code):
"""將 Base54 字串轉換回整數"""
num = decimal.Decimal(0)
for i, ch in enumerate(reversed(code)):
pos = CODES.index(ch)
num += (decimal.Decimal(54) ** i) * (pos + 1)
return int(num - 1) # 修正 0 次方偏移
# 編碼測試
for n in [0, 1, 53, 54, 100, 10000, 123456789]:
code = convert_to_code(n)
back = convert_to_num(code)
print(f'{n} -> {code} -> {back} {"✓" if n==back else "✗"}')
n = floor(n/54) - 1 處理進位邏輯,確保 0~53 直接映射單字元。num = Σ (54^i) * (pos+1),最後減 1 修正基準偏移。int 亦可無損運算。54**i 表加速解碼。shortuuid、hashids。