Bytes and binary data
suggest changeMany 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:
- the
bytetype (an alias foruint8) and byte slices[]byte - package
bytes, which does for[]bytewhat packagestringsdoes for strings bytes.Buffer, a growable buffer that is both anio.Writerand anio.Readerbytes.Reader, which turns a[]byteinto anio.Reader/io.Seeker- package
encoding/binaryfor multi-byte integers, floats and fixed-size structs encoding/hexfor looking at binary data while debugging
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:
lenof a string or a byte slice counts bytes, not characters.étakes 2 bytes in UTF-8. See Characters and runes for working with characters.[]byte(s)andstring(b)copy, so changing the slice doesn't change the string. The compiler skips the copy when it can prove that's safe, for example in map lookupsm[string(b)]and in comparisons likestring(b) == "abc".%xprints bytes as hex,% x(with a space) puts a space between bytes, and%qprints a quoted string with non-printable bytes escaped. These are the most useful verbs for looking at binary data.- printing a
[]bytewithPrintlnor%vshows decimal numbers. - byte arithmetic wraps around:
200 + 100is44(300 mod 256). - a string can hold any bytes, including invalid UTF-8 and zero bytes. Still, use
[]bytefor binary data: it can be changed in place, and it's what I/O functions take.
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"
- you can't compare byte slices with
==; it doesn't compile for slices. Usebytes.Equal.bytes.Comparereturns -1, 0 or 1, which is what sorting needs, e.g.slices.SortFunc(keys, bytes.Compare). bytes.Cutsplits around the first separator. It's usually the simplest way to parsekey=valuedata.Split,Fields,Cut,TrimSpaceand similar functions return sub-slices of the input. They share its memory and copy nothing. See Common mistakes.bytes.Lines,bytes.SplitSeqandbytes.FieldsSeq(Go 1.24+) return iterators, so they don't allocate a slice of results.bytes.ToUpper,ReplaceAll,Joinand other functions that produce new content return a newly allocated slice.
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
- the zero value
var buf bytes.Bufferis ready to use. Pass it as&buf: the methods have pointer receivers, and copying aBufferthat holds data is a bug. Write,WriteString,WriteByteandWriteRunealways return a nil error. They panic only if memory can't be allocated, so it's fine to ignore their errors.Bytes()returns the unread data without copying.String()returns it as a new string.- reading (
Read,Next,ReadByte,ReadBytes,io.ReadAll) consumes data. Once everything has been read,Readreturnsio.EOF. Reset()empties the buffer but keeps its capacity. That helps when you re-use a buffer in a loop or with sync.Pool.Grow(n)orbytes.NewBuffer(make([]byte, 0, n))allocates memory up front when you know the approximate size.
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
Readreads up tolen(p)bytes and may return fewer. When nothing is left it returns0, io.EOF.io.ReadFull(r, p)keeps reading untilpis full. If the input ends early it returnsio.ErrUnexpectedEOF, orio.EOFif no bytes were read at all. Use it to read a fixed-size record from any reader: a singleReadon a file or network connection is allowed to return only part of the data.Resetpoints an existing reader at a new slice, which saves an allocation.strings.NewReaderdoes the same for a string.
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.Sizereturns the encoded size: 4+2+2+4+4 = 16 bytes. Go may add padding to the struct in memory; the encoded form never has any.- the byte order applies to each field separately. Compare
Version(02 00vs00 02) andCountin the two dumps. binary.Readneeds a pointer. It also reads slices: withvalues := make([]uint32, n),binary.Read(r, binary.LittleEndian, values)readsnvalues.binary.Append,binary.Encodeandbinary.Decode(Go 1.23+) work on byte slices instead of readers and writers.int,uint,uintptr, strings, slices inside structs, maps and pointers have no fixed size, so they're rejected with an error.- blank fields (
_ [2]byte) are written as zeros and skipped when reading. This is handy for padding and reserved fields in file formats.
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 input is wrapped in a
bufio.Reader. Reading a file or socket a few bytes at a time without a buffer makes a system call for every field.bufio.Readeralso implementsio.ByteReader, whichbinary.ReadUvarintneeds. - each fixed-size piece is read with
io.ReadFullinto a small array, then decoded withbinary.BigEndian. Convertinguint32toint32keeps the bits as they are, so-5makes the round trip asff ff ff fb. - the magic number and version are checked first, so a file of the wrong type gets a clear error.
- errors are wrapped with
%wand say which point failed. Callers can still check forio.ErrUnexpectedEOFwitherrors.Is. - lengths and counts read from the input are checked before allocating. Without the
countcheck, a corrupted or malicious file with a huge count would makemaketry to allocate gigabytes. Theuint16name length can't exceed 64 KB, so it needs no check.
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
- slicing never copies.
wordstill points intodata, so changingdatachangesword. This matters when you keep part of a large buffer: even a small sub-slice keeps the whole buffer in memory. Usebytes.Clonewhen you need the data after you're done with the buffer it came from. appendto 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 expressionorig[:3:3]) sets the capacity equal to the length, soappendhas to allocate.- 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:
- a single
Readmay return fewer bytes than you asked for even when more data is coming. Useio.ReadFullfor fixed-size data. To read everything, useio.ReadAll, with a size limit fromio.LimitReaderfor untrusted input. binary.Writewith a struct that contains anintfails at run time, not at compile time. Use sized types likeint32anduint64.- mixing up byte order. Network protocols and most file formats (PNG, JPEG, Java class files) are big endian. Windows formats (BMP, WAV), ZIP and the fixed-size fields of Protocol Buffers are little endian. Check the specification.
- converting a length from untrusted input to
intand passing it tomakewithout checking it. string(b)on a large slice in a hot loop allocates every time. Callbytesfunctions on the slice instead.
Summary
byteisuint8, and[]byteis a normal slice.[]byte(s)andstring(b)copy the data.- print binary data with
%x,% xor%q, or usehex.Dumpto see everything - package
byteshas the same functions asstrings. Compare slices withbytes.Equal, not==. bytes.Bufferis a growable reader and writer;bytes.Readerturns a slice into a seekableio.Readerio.ReadFullreads exactly n bytes. Wrap files and sockets inbufiobefore reading small fields.encoding/binaryencodes integers and fixed-size structs in the byte order you choose- check lengths and counts read from input before allocating
- sub-slices share memory; use
bytes.Cloneorslices.Clipwhen you don't want that