Binary Write And Read Fixed Width Structs
Encode fixed-width structs with binary.Write and binary.Read so the on-disk layout is explicit, byte counts are predictable, and endianness stays controlled.
Code
package main
import (
"bytes"
"encoding/binary"
"fmt"
)
type Header struct {
Magic uint16
Version uint8
Reserved uint8
Payload uint32
}
func main() {
h := Header{Magic: 0xBEEF, Version: 2, Reserved: 0, Payload: 1024}
var buf bytes.Buffer
// BigEndian 写入:字段按声明顺序、定宽落盘,不做对齐填充
if err := binary.Write(&buf, binary.BigEndian, h); err != nil {
panic(err)
}
fmt.Printf("encoded %d bytes: % x\n", buf.Len(), buf.Bytes())
var back Header
// Read 需要指向结构的指针,精确消费结构体大小的字节
if err := binary.Read(&buf, binary.BigEndian, &back); err != nil {
panic(err)
}
fmt.Printf("decoded: %#x v%d payload=%d\n", back.Magic, back.Version, back.Payload)
}How the code behaves
Count the function main as the entire surface area of Binary Write And Read Fixed Width Structs.
Failure handling is panic(err): 2 checkpoints abort the program at the point a problem is detected.
What to watch for
- The whole dependency story is the language version itself.
panic(err)is the only failure path here: the first problem stops the program.
Applying it
The demo output is labeled (encoded, decoded:), so every line in the printed output names the step that produced it.
Statements that matter
h := Header{Magic: 0xBEEF, Version: 2, Reserved: 0, Payload: 1024}
Interactive Tools for This Topic
Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.
FAQ
- Does the snippet panic on failure?
- It stops. All 2 `if err != nil` branches ends in `panic(err)` — nothing continues past a failed call.
- What does Binary Write And Read Fixed Width Structs print when run?
- Execute the whole file; each printed line is prefixed with a label like `encoded`, `decoded:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.