Bzip2 Decompress Fixed Payload
Decompress an embedded bzip2 stream with compress/bzip2, whose streaming reader needs no output size — the package ships decompression only.
Code
package main
import (
"bytes"
"compress/bzip2"
"fmt"
"io"
)
// 71 字节的 bzip2 流(由 bzip2 -9 命令行工具生成,内容为一段英文短句)
var blob = []byte{
0x42, 0x5a, 0x68, 0x39, 0x31, 0x41, 0x59, 0x26, 0x53, 0x59, 0xb8, 0xbe,
0x88, 0xd4, 0x00, 0x00, 0x04, 0x99, 0x80, 0x40, 0x02, 0x10, 0x00, 0x3e,
0x23, 0xde, 0x70, 0x20, 0x00, 0x22, 0x26, 0x8c, 0x46, 0x83, 0x4c, 0x9a,
0x14, 0xc2, 0x69, 0xa0, 0x34, 0xc4, 0xde, 0x18, 0xd4, 0xa0, 0xd1, 0xd5,
0xaa, 0xe4, 0x32, 0x7e, 0xb3, 0x82, 0x02, 0x40, 0xc4, 0xbc, 0x4b, 0x48,
0x7c, 0x5d, 0xc9, 0x14, 0xe1, 0x42, 0x42, 0xe2, 0xfa, 0x23, 0x50,
}
func main() {
// bzip2.NewReader 边读边解压,不需要预先知道解压后的大小
text, err := io.ReadAll(bzip2.NewReader(bytes.NewReader(blob)))
if err != nil {
fmt.Println("decompress:", err)
return
}
fmt.Println("decoded:", string(text))
// 头四个字节是 BZh9 魔数:BZh 前缀 + 900k 块大小
fmt.Println("magic:", string(blob[:3]), "block size:", blob[3]-'0', "00k")
}The code in its own words
Everything happens inside the function main.
Error handling is inline: 1 place test err != nil and branch immediately.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
The declaration that anchors the file: func main()
The run reports back with labels — decompress:, decoded:, magic: — when the file runs.
Key statements
if err != nil {
fmt.Println("decompress:", err)
return
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Bzip2 Decompress Fixed Payload print when run?
- Execute the whole file; each printed line is prefixed with a label like `decompress:`, `decoded:`, `magic:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.