What is bencode?

Bencode (said "bee-encode") is the data format of BitTorrent. Every .torrent file is a bencoded dictionary, and trackers and the DHT network answer in bencode too. It knows only four kinds of values: whole numbers, strings, lists and dictionaries. Each value can be written only one way, so the same data always gives the same bytes, which is how BitTorrent can name a torrent by the hash of its info dictionary.

Tool description

Type or paste JSON into the first editor, and its bencode appears in the second one as you type, ready to copy. Insert sample fills in the details of a garden to try. Each JSON value becomes its bencode form:

  • Whole numbers go between i and e: 120 becomes i120e, and -2 becomes i-2e.
  • Text becomes its length in bytes, a colon and the text: "tulips" becomes 6:tulips.
  • Arrays become lists between l and e: ["tulips", "daisies"] becomes l6:tulips7:daisiese.
  • Objects become dictionaries between d and e, with their keys sorted: {"to": 18, "from": 9} becomes d4:fromi9e2:toi18ee.
  • true and false become 1 and 0, as bencode has no such values: {"rain": false} becomes d4:raini0ee.

To turn bencode back into JSON, press the swap button between the editors, which also moves the result into the input, or use the Bencode Decoder.

Features

  • Encodes JSON to bencode as you type
  • Sorts dictionary keys and counts string lengths in bytes, as bencode requires
  • Runs in your browser

Examples

JSON Bencode
{"name": "Birthday cake", "candles": 8, "flavors": ["vanilla", "lemon"]} d7:candlesi8e7:flavorsl7:vanilla5:lemone4:name13:Birthday cakee
{"picnic": {"guests": 6, "basket": ["bread", "cheese", "grapes"]}} d6:picnicd6:basketl5:bread6:cheese6:grapese6:guestsi6eee
"café" 5:café
"🌷" 4:🌷

What bencode can't hold

  • null: replace each one with a string, a number, a list or a dictionary, or leave its key out.
  • Numbers with a fraction, such as 2.50, as bencode has only whole numbers. Write a price as text, so "2.50" gives 4:2.50, or in cents, so 250 gives i250e. Whole numbers written with a fraction or an exponent are fine: 3.0 gives i3e, and 1e3 gives i1000e.
  • Whole numbers too large for JavaScript to hold exactly. They give an error instead of losing their last digits.

Good to know

  • Keys are sorted by their bytes: digits come before capital letters, and capitals before small letters. So {"Zinnia": 1, "aster": 2, "10": 3, "9": 4} gives d2:10i3e1:9i4e6:Zinniai1e5:asteri2ee.
  • The input has to be valid JSON, with double quotes around keys and text and no comma after the last item. Otherwise the error passes on your browser's description of the problem.
  • Bencode holds one value. To encode several, put them in a JSON array, and they become a list.