Manim 风格演示 · Base64 编码原理

← Python 程序设计 V2
STEP 0点击播放,看 3 个字符如何变成 4 个 Base64 字符。
作业②对应 · 手写 base64_encode() 的核心逻辑
def base64_encode(text: str) -> str:
    # 1. 字符串 → 字节 → 24 比特位流
    bits = "".join(format(b, "08b") for b in text.encode())
    # 2. 不足 6 的倍数就补零
    bits += "0" * (-len(bits) % 6)
    # 3. 每 6 位一组 → 查表
    idx = [int(bits[i:i+6], 2) for i in range(0, len(bits), 6)]
    out = "".join(ALPHABET[i] for i in idx)
    # 4. 每 3 字节产出 4 字符,缺位补 '='
    return out + "=" * ((3 - len(text) % 3) % 3)