What is Bencode?
Bencode is a compact serialization format comparable to JSON. It is used heavily in the BitTorrent ecosystem. For most use cases, it will result in a smaller encoding than JSON.
Data types
Bencode supports a few common data types; integer, byte array / string, list and dictionary.
Integer
Integers are encoded using the i
prefix followed by the decimal representation of the number and the e
suffix.
For example, i42e
is the Bencode representation of the number 42
.
Byte array / string
Byte arrays and strings are encoded using the length of the array/string followed by a colon :
and then the raw data.
For example, 4:spam
is the Bencode representation of the string spam
.
List
Lists are encoded using the l
prefix followed by the Bencode representations of the items in the list and the e
suffix.
For example, li42ee
is the Bencode representation of the list [42]
.
Dictionary
Dictionaries are encoded using the d
prefix followed by the Bencode representations of the keys and values in the dictionary and the e
suffix.
The keys must be byte arrays or strings and must be sorted in lexicographical order.
For example, d3:fooi42ee
is the Bencode representation of the dictionary {"foo": 42}
.