Methods for converting BN instances to various output formats including strings, arrays, buffers, and JavaScript numbers.
Convert BN instances to string representations in various bases with optional padding.
/**
* Convert to string representation
* @param {number} [base=10] - Number base (2-36) or 'hex' for base 16
* @param {number} [padding=1] - Minimum string length (pads with zeros)
* @returns {string} String representation of the number
*/
toString(base?: number, padding?: number): string;
/**
* Convert to JSON-compatible hex string
* @returns {string} Hex string representation (equivalent to toString(16, 2))
*/
toJSON(): string;Usage Examples:
const BN = require('bn.js');
const num = new BN('255');
// Different bases
console.log(num.toString()); // "255" (decimal, default)
console.log(num.toString(2)); // "11111111" (binary)
console.log(num.toString(8)); // "377" (octal)
console.log(num.toString(16)); // "ff" (hexadecimal)
console.log(num.toString(36)); // "73" (base 36)
// With padding
console.log(num.toString(16, 4)); // "00ff" (padded to 4 characters)
console.log(num.toString(2, 10)); // "0011111111" (padded to 10 characters)
// JSON format
console.log(num.toJSON()); // "ff" (hex string)
// Large numbers
const large = new BN('123456789012345678901234567890');
console.log(large.toString()); // "123456789012345678901234567890"
console.log(large.toString(16)); // "18ee90ff6c373e0ee4e3f0ad2" (hex)Convert BN instances to JavaScript numbers with safety checks for precision limits.
/**
* Convert to JavaScript number (limited to 53 bits of precision)
* @returns {number} JavaScript number representation
* @throws {Error} If the number exceeds JavaScript's safe integer range
*/
toNumber(): number;Usage Examples:
const BN = require('bn.js');
// Safe conversions
const small = new BN('42');
console.log(small.toNumber()); // 42
const mediumPositive = new BN('9007199254740991'); // Number.MAX_SAFE_INTEGER
console.log(mediumPositive.toNumber()); // 9007199254740991
const mediumNegative = new BN('-9007199254740991');
console.log(mediumNegative.toNumber()); // -9007199254740991
// This will throw an error - number too large
try {
const huge = new BN('18446744073709551616'); // 2^64
console.log(huge.toNumber()); // Error: Number can only safely store up to 53 bits
} catch (error) {
console.log('Number too large for JavaScript number type');
}Convert BN instances to byte arrays with configurable endianness and length.
/**
* Convert to byte array
* @param {string} [endian='be'] - Byte order: 'be' (big-endian) or 'le' (little-endian)
* @param {number} [length] - Desired array length (pads with zeros or validates)
* @returns {number[]} Array of bytes (0-255)
*/
toArray(endian?: string, length?: number): number[];
/**
* Convert to typed array or Array-like object
* @param {Function} ArrayType - Constructor for the array type (Array, Uint8Array, etc.)
* @param {string} [endian='be'] - Byte order: 'be' or 'le'
* @param {number} [length] - Desired array length
* @returns {ArrayType} Instance of the specified array type
*/
toArrayLike(ArrayType: Function, endian?: string, length?: number): any;Usage Examples:
const BN = require('bn.js');
const num = new BN('0x1234', 16); // 4660 decimal
// Basic array conversion
console.log(num.toArray()); // [18, 52] (big-endian bytes)
console.log(num.toArray('be')); // [18, 52] (explicit big-endian)
console.log(num.toArray('le')); // [52, 18] (little-endian)
// With specific length
console.log(num.toArray('be', 4)); // [0, 0, 18, 52] (padded to 4 bytes)
console.log(num.toArray('le', 4)); // [52, 18, 0, 0] (little-endian, padded)
// Different array types
console.log(num.toArrayLike(Array)); // [18, 52]
console.log(num.toArrayLike(Uint8Array)); // Uint8Array [18, 52]
// Larger number example
const large = new BN('0x123456', 16);
console.log(large.toArray()); // [18, 52, 86]
console.log(large.toArray('le')); // [86, 52, 18]Convert BN instances to Node.js Buffer objects when available.
/**
* Convert to Node.js Buffer (if available)
* @param {string} [endian='be'] - Byte order: 'be' or 'le'
* @param {number} [length] - Desired buffer length
* @returns {Buffer} Node.js Buffer instance
*/
toBuffer(endian?: string, length?: number): Buffer;Usage Examples:
const BN = require('bn.js');
// Only works in Node.js environment
if (typeof Buffer !== 'undefined') {
const num = new BN('0x1234', 16);
// Basic buffer conversion
const buffer1 = num.toBuffer(); // <Buffer 12 34>
const buffer2 = num.toBuffer('be'); // <Buffer 12 34> (big-endian)
const buffer3 = num.toBuffer('le'); // <Buffer 34 12> (little-endian)
// With specific length
const buffer4 = num.toBuffer('be', 4); // <Buffer 00 00 12 34>
const buffer5 = num.toBuffer('le', 4); // <Buffer 34 12 00 00>
console.log(buffer1);
console.log(buffer4);
}
// For browser compatibility, use toArrayLike instead:
const uint8Array = num.toArrayLike(Uint8Array, 'be', 4);Convert to and from two's complement representation for signed integer handling.
/**
* Convert to two's complement representation
* @param {number} width - Bit width for the two's complement representation
* @returns {BN} New BN instance in two's complement form
*/
toTwos(width: number): BN;
/**
* Convert from two's complement representation
* @param {number} width - Bit width used for the two's complement
* @returns {BN} New BN instance converted from two's complement
*/
fromTwos(width: number): BN;Usage Examples:
const BN = require('bn.js');
// Positive number to two's complement
const positive = new BN('5');
const twosComp = positive.toTwos(8);
console.log(twosComp.toString(2)); // "101" (still positive)
// Negative number to two's complement
const negative = new BN('-5');
const negTwosComp = negative.toTwos(8);
console.log(negTwosComp.toString(2)); // "11111011" (two's complement of -5 in 8 bits)
// Convert back from two's complement
const backToOriginal = negTwosComp.fromTwos(8);
console.log(backToOriginal.toString()); // "-5"
// Working with 32-bit signed integers
const value = new BN('-2147483648'); // Most negative 32-bit integer
const twos32 = value.toTwos(32);
console.log(twos32.toString(16)); // "80000000"
const backFrom32 = twos32.fromTwos(32);
console.log(backFrom32.toString()); // "-2147483648"Get information about the size and length of numbers in various units.
/**
* Get the number of bits required to represent this number
* @returns {number} Number of bits
*/
bitLength(): number;
/**
* Get the number of bytes required to represent this number
* @returns {number} Number of bytes (rounded up)
*/
byteLength(): number;
/**
* Get the number of trailing zero bits
* @returns {number} Number of consecutive zero bits from the right
*/
zeroBits(): number;Usage Examples:
const BN = require('bn.js');
const num1 = new BN('255'); // 0xFF
const num2 = new BN('256'); // 0x100
const num3 = new BN('1000'); // 0x3E8
const num4 = new BN('1024'); // 0x400
// Bit lengths
console.log(num1.bitLength()); // 8 (requires 8 bits)
console.log(num2.bitLength()); // 9 (requires 9 bits)
console.log(num3.bitLength()); // 10 (requires 10 bits)
// Byte lengths
console.log(num1.byteLength()); // 1 (fits in 1 byte)
console.log(num2.byteLength()); // 2 (requires 2 bytes)
console.log(num3.byteLength()); // 2 (requires 2 bytes)
// Trailing zero bits
console.log(num1.zeroBits()); // 0 (255 = 11111111, no trailing zeros)
console.log(num2.zeroBits()); // 8 (256 = 100000000, 8 trailing zeros)
console.log(num4.zeroBits()); // 10 (1024 = 10000000000, 10 trailing zeros)
// Practical usage - determining storage requirements
const largeNum = new BN('123456789012345678901234567890');
console.log(`Requires ${largeNum.bitLength()} bits`);
console.log(`Requires ${largeNum.byteLength()} bytes`);Utility methods for copying and cloning BN instances.
/**
* Create a copy of this BN instance
* @returns {BN} New BN instance with the same value
*/
clone(): BN;
/**
* Copy this BN's value to another BN instance
* @param {BN} dest - Destination BN instance to copy to
* @returns {BN} The destination BN instance
*/
copy(dest: BN): BN;Usage Examples:
const BN = require('bn.js');
const original = new BN('12345');
// Clone creates a new independent instance
const cloned = original.clone();
console.log(cloned.toString()); // "12345"
console.log(cloned === original); // false (different objects)
// Modify clone doesn't affect original
cloned.iaddn(1);
console.log(original.toString()); // "12345" (unchanged)
console.log(cloned.toString()); // "12346" (modified)
// Copy to existing instance
const destination = new BN('0');
original.copy(destination);
console.log(destination.toString()); // "12345"const BN = require('bn.js');
function toHexString(bn) {
return '0x' + bn.toString(16);
}
const num = new BN('255');
console.log(toHexString(num)); // "0xff"const BN = require('bn.js');
function toFixedHex(bn, bytes) {
return bn.toString(16, bytes * 2);
}
const num = new BN('255');
console.log(toFixedHex(num, 4)); // "000000ff" (4 bytes = 8 hex characters)const BN = require('bn.js');
function toSafeNumber(bn) {
const MAX_SAFE = new BN(Number.MAX_SAFE_INTEGER.toString());
const MIN_SAFE = new BN(Number.MIN_SAFE_INTEGER.toString());
if (bn.gt(MAX_SAFE) || bn.lt(MIN_SAFE)) {
throw new Error('Number exceeds safe integer range');
}
return bn.toNumber();
}
const safe = new BN('1000');
const unsafe = new BN('9007199254740992'); // MAX_SAFE_INTEGER + 1
console.log(toSafeNumber(safe)); // 1000
// console.log(toSafeNumber(unsafe)); // Throws error