Bytes and binary data

suggest change

Many programs work with raw bytes rather than text. They read file formats, speak network protocols, hash, compress, or build messages for a binary RPC. Go's basic tools for this are:

Working with individual bits (masks, flags, shifts, math/bits) is covered in Bit manipulation. Turning bytes into printable text with hex or base64 is covered in Hex, base64 encoding.

byte and []byte

A byte is an unsigned 8-bit integer. A []byte is a regular slice, so everything you know about slices applies: len, cap, append, slicing with b[i:j] and copy.

A Go string is an immutable sequence of bytes. It is usually UTF-8, but it doesn't have to be. Converting between string and []byte copies the data:

package main

import "fmt"

func main() {
	s := "héllo"
	b := []byte(s) // copies the UTF-8 bytes of the string
	fmt.Println(len(s), len(b))
	fmt.Println(b)
	fmt.Printf("%x\n", b)   // hex, no spaces
	fmt.Printf("% x\n", b)  // hex, space between bytes
	fmt.Printf("%X\n", b)   // upper case hex
	fmt.Printf("%q\n", b)   // quoted Go string
	fmt.Printf("%v\n", b[:2])

	b[0] = 'H' // modifying b doesn't change s
	fmt.Println(s, string(b))

	var x byte = 200
	x += 100 // byte is uint8: arithmetic wraps around
	fmt.Println(x)

	raw := []byte{0xff, 0xfe, 'A', 0x00}
	fmt.Printf("%q\n", string(raw)) // a string can hold any bytes
}
6 6
[104 195 169 108 108 111]
68c3a96c6c6f
68 c3 a9 6c 6c 6f
68C3A96C6C6F
"héllo"
[104 195]
héllo Héllo
44
"\xff\xfeA\x00"

Things to notice:

Package bytes

Package bytes mirrors package strings: almost every function in strings has a bytes version that takes []byte. Use it when your data is already a byte slice. Converting to a string and back just to search it costs two copies.

package main

import (
	"bytes"
	"fmt"
)

func main() {
	a := []byte("key=value; other=42")

	fmt.Println(bytes.Equal([]byte("go"), []byte("go")))
	fmt.Println(bytes.Compare([]byte("a"), []byte("b")))
	fmt.Println(bytes.HasPrefix(a, []byte("key=")))
	fmt.Println(bytes.Contains(a, []byte("other")))
	fmt.Println(bytes.Index(a, []byte(";")))
	fmt.Println(bytes.IndexByte(a, '='))

	before, after, found := bytes.Cut(a, []byte("; "))
	fmt.Printf("%q %q %v\n", before, after, found)

	for _, part := range bytes.Split(a, []byte("; ")) {
		k, v, _ := bytes.Cut(part, []byte("="))
		fmt.Printf("%s -> %s\n", k, v)
	}

	fmt.Printf("%q\n", bytes.TrimSpace([]byte("  \tpadded\r\n")))
	fmt.Printf("%q\n", bytes.Fields([]byte(" a  b\tc ")))
	fmt.Printf("%s\n", bytes.ToUpper([]byte("shout")))
	fmt.Printf("%s\n", bytes.ReplaceAll([]byte("a-b-c"), []byte("-"), []byte("+")))
	fmt.Printf("%s\n", bytes.Join([][]byte{[]byte("x"), []byte("y")}, []byte(", ")))

	// Go 1.24+: iterate lines without allocating a slice of lines
	for line := range bytes.Lines([]byte("one\ntwo\nthree")) {
		fmt.Printf("%q\n", line)
	}
}
true
-1
true
true
9
3
"key=value" "other=42" true
key -> value
other -> 42
"padded"
["a" "b" "c"]
SHOUT
a+b+c
x, y
"one\n"
"two\n"
"three"

bytes.Buffer

bytes.Buffer is a variable-sized buffer of bytes. You write at the end and read from the front. It implements io.Writer, io.Reader, io.ByteReader, io.WriterTo and io.ReaderFrom, so you can pass it to any function that takes one of those interfaces.

package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
)

func main() {
	var buf bytes.Buffer // zero value is an empty buffer ready to use
	buf.WriteString("hello")
	buf.WriteByte(',')
	buf.Write([]byte(" world"))
	fmt.Fprintf(&buf, " %d times\n", 3) // *bytes.Buffer is an io.Writer

	fmt.Println(buf.Len())
	fmt.Printf("%q\n", buf.String())

	// reading consumes data from the front
	first := buf.Next(5)
	fmt.Printf("%q\n", first)
	c, _ := buf.ReadByte()
	fmt.Printf("%q\n", c)
	rest, _ := io.ReadAll(&buf)
	fmt.Printf("%q %d\n", rest, buf.Len())

	buf.Reset() // empty again, keeps the allocated memory
	buf.WriteString("to stdout\n")
	buf.WriteTo(os.Stdout)

	// pre-size when you know roughly how much you'll write
	b2 := bytes.NewBuffer(make([]byte, 0, 1024))
	b2.WriteString("x")
	fmt.Println(b2.Len(), b2.Cap())
}
21
"hello, world 3 times\n"
"hello"
','
" world 3 times\n" 0
to stdout
1 1024

If you only build text and never read it back, use strings.Builder instead: its String() method doesn't copy.

bytes.Reader

Many APIs take an io.Reader. To pass them data that's already in memory, wrap it with bytes.NewReader. Unlike bytes.Buffer it's read-only, and it also implements io.Seeker and io.ReaderAt:

package main

import (
	"bytes"
	"fmt"
	"io"
)

func main() {
	data := []byte("0123456789")
	r := bytes.NewReader(data)

	p := make([]byte, 4)
	n, _ := r.Read(p)
	fmt.Printf("%d %q remaining=%d\n", n, p[:n], r.Len())

	r.Seek(-2, io.SeekEnd)
	n, _ = r.Read(p)
	fmt.Printf("%d %q\n", n, p[:n])

	n, err := r.Read(p)
	fmt.Println(n, err)

	// ReadAt doesn't move the position, so it's safe to call concurrently
	n, _ = r.ReadAt(p, 3)
	fmt.Printf("%q\n", p[:n])

	// io.ReadFull reads exactly len(p) bytes or returns an error
	r.Reset([]byte("abc"))
	n, err = io.ReadFull(r, p)
	fmt.Println(n, err)
}
4 "0123" remaining=6
2 "89"
0 EOF
"3456"
3 unexpected EOF

Fixed-size structs with encoding/binary

Bit manipulation covers the basics: byte order, binary.BigEndian.Uint32, PutUint32, AppendUint32 and varints. This section shows how to encode whole structs.

binary.Write and binary.Read encode values whose fields all have a fixed size: bool, int8...int64, uint8...uint64, float32, float64, arrays of these, and structs made of these. Fields are written in order, with no padding:

package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
)

// Header is a fixed-size record: every field has a fixed size.
type Header struct {
	Magic   [4]byte
	Version uint16
	Flags   uint16
	Count   uint32
	Scale   float32
}

func main() {
	h := Header{Magic: [4]byte{'D', 'A', 'T', 'A'}, Version: 2, Flags: 0x0101, Count: 1000, Scale: 0.5}

	fmt.Println(binary.Size(h)) // bytes on the wire, no padding

	var buf bytes.Buffer
	if err := binary.Write(&buf, binary.LittleEndian, h); err != nil {
		panic(err)
	}
	fmt.Printf("% x\n", buf.Bytes())

	var h2 Header
	if err := binary.Read(&buf, binary.LittleEndian, &h2); err != nil {
		panic(err)
	}
	fmt.Printf("%s %+v\n", h2.Magic[:], h2)

	// Go 1.23+: Append and Decode work on byte slices directly
	b, err := binary.Append(nil, binary.BigEndian, h)
	if err != nil {
		panic(err)
	}
	fmt.Printf("% x\n", b)
	var h3 Header
	n, err := binary.Decode(b, binary.BigEndian, &h3)
	fmt.Println(n, err, h3 == h)

	// int has no fixed size, so it can't be encoded
	type Bad struct{ N int }
	err = binary.Write(&buf, binary.LittleEndian, Bad{1})
	fmt.Println(err)
}
16
44 41 54 41 02 00 01 01 e8 03 00 00 00 00 00 3f
DATA {Magic:[68 65 84 65] Version:2 Flags:257 Count:1000 Scale:0.5}
44 41 54 41 00 02 01 01 00 00 03 e8 3f 00 00 00
16 <nil> true
binary.Write: some values are not fixed-sized in type main.Bad

binary.Read and binary.Write use reflection. They're fine for headers and configuration. On hot paths that read millions of records, decoding fields by hand with binary.BigEndian.Uint32(b[i:]) is several times faster.

Parsing a binary format

Real formats mix fixed-size fields with variable-length data, such as strings prefixed by their length, counts and optional sections. Here's a complete encoder and decoder for a small format:

package main

import (
	"bufio"
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
)

// File format:
//   magic   "PNTS"         4 bytes
//   version uint8          1 byte
//   count   uvarint        1-10 bytes
//   records count times:
//     x, y  int32 big endian, 4 bytes each
//     len   uint16 big endian
//     name  len bytes of UTF-8

var magic = []byte("PNTS")

type Point struct {
	X, Y int32
	Name string
}

func encode(points []Point) []byte {
	b := append([]byte(nil), magic...)
	b = append(b, 1) // version
	b = binary.AppendUvarint(b, uint64(len(points)))
	for _, p := range points {
		b = binary.BigEndian.AppendUint32(b, uint32(p.X))
		b = binary.BigEndian.AppendUint32(b, uint32(p.Y))
		b = binary.BigEndian.AppendUint16(b, uint16(len(p.Name)))
		b = append(b, p.Name...)
	}
	return b
}

func decode(r io.Reader) ([]Point, error) {
	br := bufio.NewReader(r) // io.ByteReader needed by ReadUvarint
	var hdr [5]byte
	if _, err := io.ReadFull(br, hdr[:]); err != nil {
		return nil, fmt.Errorf("header: %w", err)
	}
	if !bytes.Equal(hdr[:4], magic) {
		return nil, fmt.Errorf("bad magic %q", hdr[:4])
	}
	if hdr[4] != 1 {
		return nil, fmt.Errorf("unsupported version %d", hdr[4])
	}
	count, err := binary.ReadUvarint(br)
	if err != nil {
		return nil, fmt.Errorf("count: %w", err)
	}
	if count > 1_000_000 { // never trust sizes from the input
		return nil, fmt.Errorf("too many points: %d", count)
	}
	points := make([]Point, 0, count)
	var rec [10]byte
	for i := range count {
		if _, err := io.ReadFull(br, rec[:]); err != nil {
			return nil, fmt.Errorf("point %d: %w", i, err)
		}
		p := Point{
			X: int32(binary.BigEndian.Uint32(rec[0:4])),
			Y: int32(binary.BigEndian.Uint32(rec[4:8])),
		}
		name := make([]byte, binary.BigEndian.Uint16(rec[8:10]))
		if _, err := io.ReadFull(br, name); err != nil {
			return nil, fmt.Errorf("point %d name: %w", i, err)
		}
		p.Name = string(name)
		points = append(points, p)
	}
	return points, nil
}

func main() {
	data := encode([]Point{{1, 2, "a"}, {-5, 300, "home"}})
	fmt.Printf("% x\n", data)

	points, err := decode(bytes.NewReader(data))
	fmt.Println(points, err)

	_, err = decode(bytes.NewReader(data[:len(data)-2]))
	fmt.Println(err)
	fmt.Println(errors.Is(err, io.ErrUnexpectedEOF))

	_, err = decode(bytes.NewReader([]byte("GIF89a")))
	fmt.Println(err)
}
50 4e 54 53 01 02 00 00 00 01 00 00 00 02 00 01 61 ff ff ff fb 00 00 01 2c 00 04 68 6f 6d 65
[{1 2 a} {-5 300 home}] <nil>
point 1 name: unexpected EOF
true
bad magic "GIF8"

How the decoder works:

The encoder builds the whole message with append and the Append* functions. To write to a file instead, wrap the file in bufio.NewWriter and call Flush at the end. See Files and I/O for more on working with files.

Looking at binary data: hex.Dump

When you debug a parser, hex.Dump prints data in the same format as hexdump -C: offset, hex bytes and printable characters:

package main

import (
	"encoding/hex"
	"fmt"
	"os"
)

func main() {
	data := []byte("Hello, binary world!\x00\x01\x02\xff")
	fmt.Print(hex.Dump(data))

	// stream a dump of a large input without holding it all in memory
	d := hex.Dumper(os.Stdout)
	d.Write([]byte{0xde, 0xad, 0xbe, 0xef})
	d.Close()
}
00000000  48 65 6c 6c 6f 2c 20 62  69 6e 61 72 79 20 77 6f  |Hello, binary wo|
00000010  72 6c 64 21 00 01 02 ff                           |rld!....|
00000000  de ad be ef                                       |....|

hex.Dumper returns an io.WriteCloser. For example, io.TeeReader(conn, hex.Dumper(os.Stderr)) wraps a network connection so that you see every byte you receive.

Common mistakes

A byte slice refers to an underlying array, and most bugs with binary data come from forgetting that:

package main

import (
	"bytes"
	"fmt"
	"slices"
)

func main() {
	// 1. sub-slices share memory with the original
	data := []byte("hello world")
	word := data[:5]
	data[0] = 'J'
	fmt.Printf("%s\n", word)

	// keep an independent copy with bytes.Clone (or slices.Clone)
	word = bytes.Clone(data[:5])
	data[0] = 'M'
	fmt.Printf("%s %s\n", word, data)

	// 2. append to a sub-slice can overwrite the original
	orig := []byte("abcdef")
	head := orig[:3]
	head = append(head, 'X')
	fmt.Printf("%s\n", orig)
	head = slices.Clip(orig[:3]) // cap == len, so append must copy
	head = append(head, 'Y')
	fmt.Printf("%s %s\n", orig, head)

	// 3. Buffer.Bytes() is only valid until the next write
	var buf bytes.Buffer
	buf.WriteString("first")
	b := buf.Bytes()
	buf.Reset()
	buf.WriteString("XXXXX")
	fmt.Printf("%s\n", b)
}
Jello
Jello Mello world
abcXef
abcXef abcY
XXXXX
  1. slicing never copies. word still points into data, so changing data changes word. This matters when you keep part of a large buffer: even a small sub-slice keeps the whole buffer in memory. Use bytes.Clone when you need the data after you're done with the buffer it came from.
  2. append to a sub-slice with spare capacity writes into the original array. orig[:3] has capacity 6, so appending 'X' overwrote 'd'. slices.Clip (or the full slice expression orig[:3:3]) sets the capacity equal to the length, so append has to allocate.
  3. the slice returned by bytes.Buffer.Bytes(), bufio.Reader.Peek(), bufio.Scanner.Bytes() and similar methods is only valid until the next call that changes the buffer. Copy it if you need it later.

Other things to watch out for:

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents