encoding/binary

Guided tour · Encoding · pkg.go.dev →

Read and write fixed-size binary numbers. Big-endian, little-endian, and variable-length (varint).

Byte orders

binary.BigEndian and binary.LittleEndian are values implementing ByteOrder. Use BigEndian for network protocols (aka 'network byte order'), LittleEndian for most on-disk formats.

Fixed-width integers

PutUint32 / Uint32 — []byte round-trip

buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, 0xDEADBEEF)
fmt.Printf("% x\n", buf)               // de ad be ef
fmt.Printf("%x\n", binary.BigEndian.Uint32(buf))

Read / Write — streaming over a Reader/Writer

Encodes any fixed-size type: numbers, arrays, and structs of fixed-size fields (no slices, no strings).

type Header struct {
    Magic uint32
    Size  uint64
}

var h Header
err := binary.Read(r, binary.BigEndian, &h)

Variable-length (varint)

Compact encoding where small numbers take fewer bytes. Used by protobuf and many wire formats.

Uvarint and Varint

buf := make([]byte, binary.MaxVarintLen64)
n := binary.PutUvarint(buf, 12345)
fmt.Printf("% x\n", buf[:n])

v, _ := binary.Uvarint(buf)
fmt.Println(v)

Append variants (1.19+)

AppendUvarint, AppendUint32 — allocation-friendly

b := []byte{}
b = binary.BigEndian.AppendUint32(b, 42)
b = binary.AppendUvarint(b, 12345)