🛠️ToolsShed

Base85 Encoder / Decoder

Encode and decode text using Base85 (ASCII85) and RFC 1924 encoding.

About Base85

Base85 encodes binary data using 85 printable ASCII characters. ASCII85 is used in PDF and PostScript. RFC 1924 uses a different character set.

Preguntas Frecuentes

Implementación de Código

import struct

def encode_ascii85(data: bytes) -> str:
    result = []
    for i in range(0, len(data), 4):
        chunk = data[i:i+4]
        padded = chunk.ljust(4, b'\x00')
        n = struct.unpack('>I', padded)[0]
        if n == 0 and len(chunk) == 4:
            result.append('z')
        else:
            chars = []
            for _ in range(5):
                chars.append(chr(n % 85 + 33))
                n //= 85
            result.extend(reversed(chars[:len(chunk)+1]))
    return '<~' + ''.join(result) + '~>'

def decode_ascii85(s: str) -> bytes:
    s = s.strip()
    if s.startswith('<~') and s.endswith('~>'):
        s = s[2:-2]
    result = bytearray()
    i = 0
    while i < len(s):
        if s[i] == 'z':
            result.extend(b'\x00' * 4); i += 1
        else:
            chunk = s[i:i+5]
            n = sum((ord(c) - 33) * (85 ** (4 - j)) for j, c in enumerate(chunk))
            result.extend(struct.pack('>I', n)[:len(chunk)-1])
            i += 5
    return bytes(result)

text = "Hello, World!"
encoded = encode_ascii85(text.encode())
print("Encoded:", encoded)
print("Decoded:", decode_ascii85(encoded).decode())

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.