LEB128 (Little Endian Base 128) Encoder/Decoder

1.0.9 · active · verified Thu Apr 09

The `leb128` Python library provides functionality for encoding and decoding integers using the LEB128 (Little Endian Base 128) variable-length compression format. This format is commonly used in contexts like the DWARF debug file format and WebAssembly binary encoding for integer literals. The library supports both unsigned and signed LEB128 operations. It is currently at version 1.0.9 and appears to have a stable, though infrequent, release cadence, with the latest release in January 2026.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates encoding and decoding both unsigned and signed integers using the `leb128` library. It uses `io.BytesIO` as a file-like object for writing and reading the LEB128 encoded bytes, highlighting the necessity to `seek(0)` the buffer before decoding after an encode operation.

import io
import leb128

# --- Unsigned LEB128 ---
# Encode an unsigned integer
unsigned_value = 624485
buf_u = io.BytesIO()
leb128.u.encode(buf_u, unsigned_value)
print(f"Encoded {unsigned_value} (unsigned): {buf_u.getvalue().hex()}")

# To decode, reset buffer position and read
buf_u.seek(0)
decoded_u = leb128.u.decode(buf_u)
print(f"Decoded unsigned: {decod_u}")
assert decoded_u == unsigned_value

# --- Signed LEB128 ---
# Encode a signed integer
signed_value = -12345
buf_i = io.BytesIO()
leb128.i.encode(buf_i, signed_value)
print(f"Encoded {signed_value} (signed): {buf_i.getvalue().hex()}")

# To decode, reset buffer position and read
buf_i.seek(0)
decoded_i = leb128.i.decode(buf_i)
print(f"Decoded signed: {decod_i}")
assert decoded_i == signed_value

print("LEB128 encoding and decoding successful!")

view raw JSON →