← All notes

encoding/hex: hexadecimal encoding and decoding

Answer: Package hex encodes and decodes hexadecimal data. Encode writes two encoded bytes for each source byte, since EncodedLen returns n 2. Decode needs an even-length string of hex characters. EncodedLen is n 2. DecodedLen is x / 2.

Encode and decode

The hex package is there to encode and decode hexadecimal data.

Encode writes into dst, using EncodedLen(len(src)) bytes.

The count it returns is always that same EncodedLen value.

EncodedLen is the size of an encoding of n bytes, which is n * 2.

Decode writes into a buffer of length DecodedLen(len(src)) and reports how many bytes it wrote.

The input must be even in length and contain only hexadecimal characters.

On a bad input, Decode reports how far it got before the error.

Length errors and helpers

DecodedLen is the size of a decoding of x bytes, which is x / 2.

ErrLength is the error for an odd-length input to Decode or DecodeString.

The stream-based Decoder returns io.ErrUnexpectedEOF instead of ErrLength.

InvalidByteError is the error type for a bad byte in a hex string.

AppendEncode appends the hexadecimally encoded src to dst and returns the extended buffer.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Go, encoding/hex package reference; Go, encoding/hex/hex.go source. BSD-3-Clause (https://go.dev/LICENSE). Copyright The Go Authors. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Go, encoding/hex package reference; Go, encoding/hex/hex.go source. BSD-3-Clause (https://go.dev/LICENSE). Copyright The Go Authors.

Cite this

Permanent ID: iil:note:k5ykwwjr

iinventedlight. 2026. "encoding/hex: hexadecimal encoding and decoding." iinventedlight Library, iil:note:k5ykwwjr, version of 2026-11-23. https://iinventedlight.com/library/notes/go-encoding-hex/. License: CC-BY-4.0.

@misc{iil_note_k5ykwwjr,
  author = {{iinventedlight}},
  title = {{encoding/hex: hexadecimal encoding and decoding}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-23},
  url = {https://iinventedlight.com/library/notes/go-encoding-hex/},
  note = {Permanent ID iil:note:k5ykwwjr. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/go-encoding-hex.md.