Python Varint Implementation

1.0.2 · maintenance · verified Thu Apr 16

The `varint` library provides a simple Python implementation for variable-length encoding and decoding of integers. This encoding scheme is primarily useful for creating more compact representations, particularly for sequences or arrays of frequently small integers, to save memory. While Python's native integer objects have overhead, varint encoding can be advantageous when storing many small numbers in a bytearray.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to encode an integer into variable-length bytes and then decode it back using both `decode_bytes` for a direct bytes object and `decode_stream` for a file-like object (BytesIO).

from varint import encode, decode_bytes, decode_stream
from io import BytesIO

# Encode an integer
number_to_encode = 300
encoded_bytes = encode(number_to_encode)
print(f"Encoded {number_to_encode}: {encoded_bytes.hex()}")

# Decode from bytes
decoded_number_from_bytes = decode_bytes(encoded_bytes)
print(f"Decoded from bytes: {decoded_number_from_bytes}")

# Decode from a stream
stream = BytesIO(encoded_bytes)
decoded_number_from_stream = decode_stream(stream)
print(f"Decoded from stream: {decoded_number_from_stream}")

# Example with a larger number
large_number = 123456789
encoded_large = encode(large_number)
print(f"\nEncoded {large_number}: {encoded_large.hex()}")
decoded_large = decode_bytes(encoded_large)
print(f"Decoded large number: {decoded_large}")

view raw JSON →