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))
encoding/binaryRead and write fixed-size binary numbers. Big-endian, little-endian, and variable-length (varint).
binary.BigEndian and binary.LittleEndian are values implementing ByteOrder. Use BigEndian for network protocols (aka 'network byte order'), LittleEndian for most on-disk formats.
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))
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)
Compact encoding where small numbers take fewer bytes. Used by protobuf and many wire formats.
buf := make([]byte, binary.MaxVarintLen64)
n := binary.PutUvarint(buf, 12345)
fmt.Printf("% x\n", buf[:n])
v, _ := binary.Uvarint(buf)
fmt.Println(v)
b := []byte{}
b = binary.BigEndian.AppendUint32(b, 42)
b = binary.AppendUvarint(b, 12345)