← 中文资源

简体中文版本

Ascii85 编码与解码

用 encoding/ascii85 把二进制字节编码成可打印文本,再解码回来:MaxEncodedLen 预留缓冲区,Decode 返回写入与消费的字节数。

阅读英文原文

实现说明

底层就是函数 main。 err 在 1 个调用点被检查,之后才会使用其他结果。

使用要点

  • 这里没有依赖树——平台本身就是全部依赖。
  • 演示输出是带标签的(encoded:、encoded bytes:、decode failed:),每个操作都会留下自己的一行标注。

常见问题

运行「Ascii85 编码与解码」会打印什么?

整个文件跑完,输出行以 encoded:、encoded bytes:、decode failed: 这类前缀开头。

签名一览:func main()

核心语句

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

代码示例

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))
}