Dev tools

VarInt (LEB128) encode / decode

LEB128-style variable-length integer encoding, the same scheme protobuf and WASM use for compact integers. Encode extracts every digit run from the input text; decode reads raw LEB128 bytes. Runs on your device.

Runs on your device. The file is never uploaded.

VarInt (LEB128) encode / decode reads the integers out of a text file and writes them as LEB128 bytes in hex, the compact scheme protobuf and WebAssembly use. Setting mode to decode runs the other way, printing the values comma separated. Signed is off by default, so a negative number is refused until you switch zigzag mapping on.

Input

Options

Questions

What is a varint?

A variable-length integer. Small numbers take one byte and large ones take more, with seven bits of value per byte and the top bit set to say another byte follows. This tool implements the LEB128 form, the same scheme Protocol Buffers and WebAssembly use to keep integers compact.

How do I encode numbers with it?

Leave mode on encode and drop a text file with your numbers in it. The tool pulls out every run of digits it finds, with an optional leading minus, so 1, 2, 3 and 1 2 3 and even prose with numbers in it all work. The output is the encoded bytes as space-separated hex. If it finds nothing it stops with "no integers found in input text to encode".

Why did I get "encoded value must be non-negative after zigzag mapping"?

You encoded a negative number with the signed option off. Plain LEB128 here only takes non-negative values. Turn on signed, which applies zigzag mapping so minus 1 becomes 1, 1 becomes 2 and so on, and negatives encode compactly and round-trip correctly.

What does the signed option do?

It switches zigzag mapping on for both directions, and it is off by default. With it on, values alternate between positive and negative as the encoded number grows, which keeps small negative numbers to one byte. You must use the same setting for encode and decode, or the numbers will come back wrong rather than failing.

How do I decode bytes back to numbers?

Switch mode to decode and drop a file containing the raw LEB128 bytes; the result is the values separated by commas. Note that encode writes hex text, not bytes, so to round-trip your own output run it through From hexdump first to turn the hex back into a .bin file.

What does "truncated varint at end of input" mean?

The last byte of your file still had its continuation bit set, so the decoder ran out of input mid-number. Either the file was cut short or it is not LEB128 at all. Check that you decoded raw bytes rather than a hex or text representation of them.

Related Dev tools