base85理解

python实现

# 字符集
table = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstu"

def base85_encode(data):
    encoded_data = ""
    padding = 0
    remainder = len(data) % 4

    # 添加填充字节
    if remainder != 0:
        padding = 4 - remainder
        data += b'\x00' * padding  #填充0

    # 将每4个字节编码为5个字符
    for i in range(0, len(data), 4):
        value = int.from_bytes(data[i:i+4], byteorder='big')
        encoded_value = ""
        for j in range(5):
            encoded_value = table[value % 85] + encoded_value
            value //= 85
        encoded_data += encoded_value

    # 移除填充字符
    if remainder != 0:
        encoded_data = encoded_data[:-padding]

    return encoded_data

def base85_decode(data):
    decoded_data = b""
    padding = 0
    remainder = len(data) % 5

    # 添加填充字符
    if remainder != 0:
        padding = 5 - remainder
        data += 'u' * padding

    # 将每5个字符解码为4个字节
    for i in range(0, len(data), 5):
        value = 0
        for j in range(5):
            value = value * 85 + table.index(data[i + j])
        decoded_value = value.to_bytes(4, byteorder='big')
        decoded_data += decoded_value

    # 移除填充字节
    if remainder != 0:
        decoded_data = decoded_data[:-padding]

    return decoded_data

# 测试
data = b"Hello, World!"
encoded_data = base85_encode(data)
decoded_data = base85_decode(encoded_data)

print("原始数据:", data)
print("编码后:", encoded_data)
print("解码后:", decoded_data)
摘自https://blog.csdn.net/u010634139/article/details/143201011

Base85是通过五次循环将每四位(不足添table[0])转五位,索引为四字节的值模85,每次循环后整除85

案例1(出自极客大挑战2024 贝斯)

image-20241124153458928

posted @ 2024-11-24 19:09  结城希亚  阅读(12)  评论(0编辑  收藏  举报