or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

arithmetic.mdbitwise.mdcomparison.mdconversion.mdindex.mdreduction.md
tile.json

tessl/npm-bn-js

Big number implementation in pure javascript for arbitrary precision arithmetic

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/bn.js@5.2.x

To install, run

npx @tessl/cli install tessl/npm-bn-js@5.2.0

index.mddocs/

BN.js

BN.js is a pure JavaScript library for big number arithmetic that enables working with arbitrarily large integers beyond JavaScript's native number limitations. It provides comprehensive mathematical operations optimized for cryptographic applications and high-precision calculations, with special performance optimizations for 256-bit numbers commonly used in elliptic curve cryptography.

Package Information

  • Package Name: bn.js
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install bn.js

Core Imports

const BN = require('bn.js');

For ES modules:

import BN from 'bn.js';

Basic Usage

const BN = require('bn.js');

// Create big numbers from various inputs
const a = new BN('dead', 16);        // From hex string
const b = new BN('101010', 2);       // From binary string  
const c = new BN(12345);             // From JavaScript number
const d = new BN([0xde, 0xad]);      // From byte array

// Perform arithmetic operations
const sum = a.add(b);
const product = a.mul(c);
const quotient = a.div(b);

// Convert back to different formats
console.log(sum.toString(10));       // Decimal string
console.log(product.toString(16));   // Hex string
console.log(quotient.toNumber());    // JavaScript number (if fits)

Architecture

BN.js is built around several key components:

  • Core BN Class: Main constructor and instance methods for number operations
  • Static Utilities: Helper functions like BN.isBN(), BN.max(), BN.min()
  • Reduction Contexts: Optimized modular arithmetic using Montgomery multiplication and Mersenne primes
  • Multiple Input Formats: Support for strings (any base 2-36), numbers, arrays, and buffers
  • Immutable Operations: Most operations return new instances; mutable variants prefixed with 'i'
  • Flexible Endianness: Support for both big-endian and little-endian byte operations

Capabilities

Number Construction and Static Methods

Core constructor and static utilities for creating and working with big numbers.

/**
 * Big number constructor
 * @param {string|number|Array|BN} number - Input value
 * @param {number|string} [base=10] - Number base (2-36) or 'hex'  
 * @param {string} [endian='be'] - Byte order: 'be' or 'le'
 */
function BN(number, base, endian);

/** Check if object is a BN instance */
BN.isBN(object: any): boolean;

/** Return the larger of two BN numbers */
BN.max(left: BN, right: BN): BN;

/** Return the smaller of two BN numbers */
BN.min(left: BN, right: BN): BN;

/** Create a copy of this BN instance */
clone(): BN;

/** Copy this BN's value to another BN instance */
copy(dest: BN): BN;

/** Word size constant (26 bits) */
BN.wordSize: number;

Arithmetic Operations

Comprehensive arithmetic operations including addition, subtraction, multiplication, division, and exponentiation.

/** Addition */
add(num: BN): BN;
iadd(num: BN): BN;        // In-place
addn(num: number): BN;    // Add JavaScript number
iaddn(num: number): BN;   // In-place add JavaScript number

/** Subtraction */
sub(num: BN): BN;
isub(num: BN): BN;        // In-place
subn(num: number): BN;    // Subtract JavaScript number
isubn(num: number): BN;   // In-place subtract JavaScript number

/** Multiplication */
mul(num: BN): BN;
imul(num: BN): BN;        // In-place
muln(num: number): BN;    // Multiply by JavaScript number  
imuln(num: number): BN;   // In-place multiply by JavaScript number

/** Division and modulo */
div(num: BN): BN;
mod(num: BN): BN;
divmod(num: BN, mode?: string, positive?: boolean): {div: BN, mod: BN};

Arithmetic Operations

Conversion and Output

Methods for converting BN instances to strings, arrays, buffers, and other formats.

/** String conversion with optional base and padding */
toString(base?: number, padding?: number): string;

/** Convert to JavaScript number (limited to 53 bits) */
toNumber(): number;

/** Convert to JSON hex string */
toJSON(): string;

/** Convert to byte array */
toArray(endian?: string, length?: number): number[];

/** Convert to Buffer (Node.js) */
toBuffer(endian?: string, length?: number): Buffer;

/** Get number of bits required to represent this number */
bitLength(): number;

/** Get number of bytes required to represent this number */
byteLength(): number;

/** Get number of trailing zero bits */
zeroBits(): number;

Conversion and Output

Comparison and Boolean Tests

Methods for comparing BN instances and testing number properties.

/** Compare with another BN (-1, 0, 1) */
cmp(num: BN): number;
cmpn(num: number): number;

/** Equality tests */
eq(num: BN): boolean;
eqn(num: number): boolean;

/** Greater than / less than */
gt(num: BN): boolean;
lt(num: BN): boolean;
gte(num: BN): boolean;
lte(num: BN): boolean;

/** Property tests */
isZero(): boolean;
isNeg(): boolean;
isEven(): boolean;
isOdd(): boolean;

Comparison and Tests

Bitwise Operations

Complete set of bitwise operations including AND, OR, XOR, shifts, and bit manipulation.

/** Bitwise logical operations */
and(num: BN): BN;
or(num: BN): BN;
xor(num: BN): BN;

/** Bit shifting */
shln(bits: number): BN;     // Shift left
shrn(bits: number): BN;     // Shift right

/** Bit manipulation */
testn(bit: number): boolean;  // Test if bit is set
setn(bit: number, val: boolean): BN;  // Set bit value

Bitwise Operations

Modular Arithmetic and Reduction

Advanced modular arithmetic with optimization contexts for cryptographic operations.

/** Create reduction context */
BN.red(modulus: BN): Red;
BN.mont(modulus: BN): Mont;

/** Convert to reduction context */
toRed(ctx: Red): BN;
fromRed(): BN;

/** Modular operations in reduction context */
redAdd(num: BN): BN;
redMul(num: BN): BN;
redPow(num: BN): BN;
redInvm(): BN;

Modular Arithmetic

Core Types

/**
 * BN class represents an arbitrary precision integer
 */
class BN {
  /** The sign: 0 for positive/zero, 1 for negative */
  negative: number;
  
  /** Array of 26-bit words representing the number */
  words: number[];
  
  /** Number of words used */
  length: number;
  
  /** Reduction context (if any) */
  red: Red | null;
}

/**
 * Reduction context for optimized modular arithmetic
 */
interface Red {
  /** The modulus */
  m: BN;
  
  /** Prime context (if using named prime) */
  prime: any | null;
}

Key Features

  • Pure JavaScript: No dependencies, works in all environments
  • Arbitrary Precision: No practical size limitations
  • Performance Optimized: Special optimizations for 256-bit numbers
  • Cryptographic Ready: Built-in support for common cryptographic primes
  • Multiple Input Formats: Strings, numbers, arrays, buffers
  • Flexible Base Support: Any base from 2 to 36
  • Immutable and Mutable: Both immutable operations and in-place variants
  • Comprehensive API: Over 120 methods covering all mathematical operations