Ascii85 Encode And Decode

Pack binary bytes into printable Ascii85 text with encoding/ascii85, then decode the result and confirm a byte-exact round trip.

GoData Integrity

Code

gosnippet
26 lines
package main

import (
	"encoding/ascii85"
	"fmt"
)

func main() {
	payload := []byte("binary payload: 0x00 0x01 0x02 0xff")

	// MaxEncodedLen 给出目标缓冲区的安全上界
	dst := make([]byte, ascii85.MaxEncodedLen(len(payload)))
	n := ascii85.Encode(dst, payload)
	fmt.Println("encoded:", string(dst[:n]))
	fmt.Println("encoded bytes:", n)

	// Decode 返回写入的字节数;空白字符由调用方自行处理
	decoded := make([]byte, len(payload))
	ndst, nsrc, err := ascii85.Decode(decoded, dst[:n], true)
	if err != nil {
		fmt.Println("decode failed:", err)
		return
	}
	fmt.Println("decoded bytes:", ndst, "consumed:", nsrc)
	fmt.Println("roundtrip:", string(decoded[:ndst]) == string(payload))
}

Under the hood

The compact reading: all the work lives in the function main, doing all the work.

err is inspected at 1 call site before any result is trusted.

Caveats

  • The language toolchain itself is the one real prerequisite.

Applying it

The main signature reads func main()

Each run prints the 5 labeled blocks encoded:, encoded bytes:, decode failed:, decoded bytes:, roundtrip: in source order.

Statements that matter

if err != nil {
	fmt.Println("decode failed:", err)
	return
}
dst := make([]byte, ascii85.MaxEncodedLen(len(payload)))
decoded := make([]byte, len(payload))

Interactive Tools for This Topic

FAQ

What does Ascii85 Encode And Decode print when run?
Execute the whole file; each printed line is prefixed with a label like `encoded:`, `encoded bytes:`, `decode failed:`.