Bencode Format: Torrent Data Structures Explained
Bencoding is the serialization format used by the BitTorrent protocol
to structure metadata in .torrent files and manage tracker
communications. Designed to be both human-readable and computationally
lightweight, Bencoding supports exactly four fundamental data types:
byte strings, integers, lists, and dictionaries. This guide outlines the
exact specification, syntax rules, and encoding examples for each of
these four core data structures.
1. Integers
Integers are encoded using an ASCII format delimited by a leading
i and a trailing e.
- Syntax:
i<integer in base 10 ASCII>e - Rules:
- Must be represented in base-10 ASCII digits.
- Negative numbers are prefixed with a minus sign (e.g.,
i-42e). - Leading zeros are not allowed (e.g.,
i03eis invalid), except for zero itself (i0e). - Negative zero (
i-0e) is invalid.
- Examples:
i42erepresents the integer42i-15erepresents the integer-15i0erepresents the integer0
2. Byte Strings
Byte strings (often referred to simply as strings) do not use a starting delimiter. Instead, they are prefixed with their byte length followed by a colon and the raw byte data.
- Syntax:
<length>:<raw bytes> - Rules:
- The length must be a non-negative base-10 integer.
- The colon (
:) acts as the separator. - The payload can contain arbitrary binary data, not just printable ASCII/UTF-8 text (for example, 20-byte SHA-1 info hashes).
- Examples:
4:spamrepresents the string"spam"0:represents an empty string""12:hello world!represents the string"hello world!"
3. Lists
Lists are ordered collections of values. A list begins with the
character l (lowercase L) and terminates with the character
e.
- Syntax:
l<bencoded elements>e - Rules:
- Elements are concatenated together sequentially with no delimiters or commas between them.
- Lists can be heterogeneous, containing any combination of Bencoded integers, strings, lists, or dictionaries.
- Empty lists are valid.
- Examples:
l4:spami42eerepresents["spam", 42]lerepresents an empty list[]ll4:spamei10eerepresents a nested list[["spam"], 10]
4. Dictionaries
Dictionaries represent associative arrays (key-value maps). A
dictionary begins with the character d and terminates with
the character e.
- Syntax:
d<key1><value1><key2><value2>...e - Rules:
- Keys must be Bencoded byte strings.
- Values can be any valid Bencoded data type (integer, string, list, or dictionary).
- Ordering: Keys must appear in strict lexicographical order based on their raw byte values (not alphabetical order according to localized collations).
- Duplicate keys are not permitted.
- Examples:
d3:agei25e4:name4:Johnerepresents{"age": 25, "name": "John"}(keys"age"and"name"are sorted)derepresents an empty dictionary{}d4:spaml1:a1:beerepresents{"spam": ["a", "b"]}