LEB128 Encoding and Decoding Utilities

1.0.0 · active · verified Sun Apr 19

The `leb` Node.js module provides a suite of utility functions for encoding and decoding integers using the LEB128 (Little-Endian Base 128) variable-length representation format. It supports both signed and unsigned values, with options for 32-bit integers, 64-bit integers (which return a `lossy` flag due to JavaScript's number precision limitations), and arbitrary-length buffer representations. Currently at `v1.0.0`, the package was recently resurrected and aims to provide a reliable, dependency-free solution for LEB128, a format notably used in the DWARF 3 debugging format and Android's DEX file format. The package maintains a stable API with no breaking changes in its recent major release and focuses on direct encoding/decoding operations for binary data within Node.js environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to encode and decode both signed and unsigned 32-bit integers using `leb`, including handling offsets in a concatenated buffer.

import { encodeInt32, decodeInt32, encodeUInt32, decodeUInt32 } from 'leb';

// Example: Encoding and decoding a signed 32-bit integer
const signedNumber = -1234567;
const encodedSigned = encodeInt32(signedNumber);
console.log(`Encoded signed ${signedNumber}: ${encodedSigned.toString('hex')}`);
const decodedSigned = decodeInt32(encodedSigned);
console.log(`Decoded signed: ${decodedSigned.value} (nextIndex: ${decodedSigned.nextIndex})`);

// Example: Encoding and decoding an unsigned 32-bit integer
const unsignedNumber = 4294967295; // Max UInt32
const encodedUnsigned = encodeUInt32(unsignedNumber);
console.log(`Encoded unsigned ${unsignedNumber}: ${encodedUnsigned.toString('hex')}`);
const decodedUnsigned = decodeUInt32(encodedUnsigned);
console.log(`Decoded unsigned: ${decodedUnsigned.value} (nextIndex: ${decodedUnsigned.nextIndex})`);

// Example with an offset in a larger buffer
const multiValueBuffer = Buffer.concat([
  encodeInt32(100),
  encodeInt32(-500),
  encodeUInt32(250)
]);

let currentOffset = 0;
let result1 = decodeInt32(multiValueBuffer, currentOffset);
console.log(`
Value 1: ${result1.value}`);
currentOffset = result1.nextIndex;

let result2 = decodeInt32(multiValueBuffer, currentOffset);
console.log(`Value 2: ${result2.value}`);
currentOffset = result2.nextIndex;

let result3 = decodeUInt32(multiValueBuffer, currentOffset);
console.log(`Value 3: ${result3.value}`);
console.log(`Final offset: ${result3.nextIndex}`);

view raw JSON →