Top Related Projects
A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
An arbitrary length integer library for Javascript
An extensive math library for JavaScript and Node.js
Quick Overview
bn.js is a lightweight, high-performance JavaScript library for working with Big Numbers. It provides efficient arithmetic operations and utilities for handling large integers, making it particularly useful for cryptography, financial calculations, and other applications requiring precise numerical computations beyond JavaScript's native number capabilities.
Pros
- High performance and optimized for speed
- Supports both Node.js and browser environments
- Comprehensive API for various arithmetic and bitwise operations
- Well-maintained and actively developed
Cons
- Limited to integer operations (no floating-point support)
- May have a steeper learning curve compared to native JavaScript numbers
- Potential overhead for simple calculations that don't require big number precision
- Not as feature-rich as some other big number libraries (e.g., decimal.js)
Code Examples
- Basic arithmetic operations:
const BN = require('bn.js');
const a = new BN('1234567890');
const b = new BN('9876543210');
console.log(a.add(b).toString()); // Addition: 11111111100
console.log(a.mul(b).toString()); // Multiplication: 12193263111263526900
- Modular exponentiation (useful in cryptography):
const BN = require('bn.js');
const base = new BN('2');
const exponent = new BN('256');
const modulus = new BN('1000000007');
const result = base.pow(exponent).mod(modulus);
console.log(result.toString()); // 616556524
- Bitwise operations:
const BN = require('bn.js');
const a = new BN('1010', 2); // Binary: 1010 (Decimal: 10)
const b = new BN('1100', 2); // Binary: 1100 (Decimal: 12)
console.log(a.and(b).toString(2)); // Bitwise AND: 1000
console.log(a.or(b).toString(2)); // Bitwise OR: 1110
console.log(a.xor(b).toString(2)); // Bitwise XOR: 0110
Getting Started
To use bn.js in your project, first install it via npm:
npm install bn.js
Then, in your JavaScript file:
const BN = require('bn.js');
// Create a new BN instance
const num = new BN('123456789');
// Perform operations
const result = num.add(new BN('987654321'));
console.log(result.toString()); // 1111111110
For browser usage, you can include bn.js via a CDN or bundle it with your application using a module bundler like webpack or Rollup.
Competitor Comparisons
A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
Pros of bignumber.js
- More comprehensive documentation and examples
- Supports decimal arithmetic with configurable precision
- Offers a wider range of mathematical operations
Cons of bignumber.js
- Slower performance for large integer operations
- Larger file size, which may impact load times in browser environments
Code Comparison
bn.js:
const BN = require('bn.js');
const a = new BN('123456789');
const b = new BN('987654321');
const result = a.mul(b);
console.log(result.toString()); // 121932631112635269
bignumber.js:
const BigNumber = require('bignumber.js');
const a = new BigNumber('123456789');
const b = new BigNumber('987654321');
const result = a.multipliedBy(b);
console.log(result.toString()); // 121932631112635269
Both libraries provide similar functionality for basic arithmetic operations, but their APIs differ slightly. bn.js focuses on integer operations and is often used in cryptography-related applications, while bignumber.js offers more flexibility with decimal arithmetic and a wider range of mathematical functions.
The choice between the two depends on specific project requirements, such as performance needs, decimal precision, and the types of mathematical operations required.
An arbitrary length integer library for Javascript
Pros of BigInteger.js
- Simpler API with fewer methods, making it easier to learn and use
- Supports decimal string input and output, useful for financial calculations
- Includes built-in support for prime number operations
Cons of BigInteger.js
- Generally slower performance compared to bn.js
- Less actively maintained, with fewer recent updates
- Lacks some advanced cryptographic operations found in bn.js
Code Comparison
BigInteger.js:
var a = BigInteger("123456789");
var b = BigInteger("987654321");
var sum = a.add(b);
console.log(sum.toString()); // Output: "1111111110"
bn.js:
const BN = require('bn.js');
const a = new BN('123456789');
const b = new BN('987654321');
const sum = a.add(b);
console.log(sum.toString(10)); // Output: "1111111110"
Both libraries provide similar functionality for basic arithmetic operations, but bn.js requires explicit base specification for string conversion. BigInteger.js offers a more straightforward API, while bn.js provides more advanced features and better performance for complex calculations, especially in cryptographic applications.
An extensive math library for JavaScript and Node.js
Pros of mathjs
- Comprehensive mathematical library with support for various operations beyond big numbers
- Extensive documentation and examples
- Supports both node.js and browser environments
Cons of mathjs
- Larger file size and potentially slower performance for basic big number operations
- More complex API for simple big number calculations
- Higher learning curve for basic use cases
Code Comparison
bn.js:
const BN = require('bn.js');
const a = new BN('123456789');
const b = new BN('987654321');
const result = a.add(b);
console.log(result.toString()); // Output: 1111111110
mathjs:
const math = require('mathjs');
const a = math.bignumber('123456789');
const b = math.bignumber('987654321');
const result = math.add(a, b);
console.log(result.toString()); // Output: 1111111110
Both libraries provide similar functionality for big number arithmetic, but mathjs offers a more extensive set of mathematical operations beyond just big numbers. bn.js is more focused and potentially more efficient for specific big number use cases, while mathjs provides a broader range of mathematical tools at the cost of a larger library size and potentially more complex API for simple operations.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
BigNum in pure javascript
Install
npm install --save bn.js
Usage
const BN = require('bn.js');
var a = new BN('dead', 16);
var b = new BN('101010', 2);
var res = a.add(b);
console.log(res.toString(10)); // 57047
Note: decimals are not supported in this library.
Sponsors
My Open Source work is supported by Scout APM and
other sponsors.
Notation
Prefixes
There are several prefixes to instructions that affect the way they work. Here is the list of them in the order of appearance in the function name:
i
- perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costsu
- unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations likemod()
. In such cases if the result will be negative - modulo will be added to the result to make it positive
Postfixes
n
- the argument of the function must be a plain JavaScript Number. Decimals are not supported. The number passed must be smaller than 0x4000000 (67_108_864). Otherwise, an error is thrown.rn
- both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported.
Examples
a.iadd(b)
- perform addition ona
andb
, storing the result ina
a.umod(b)
- reducea
modulob
, returning positive valuea.iushln(13)
- shift bits ofa
left by 13
Instructions
Prefixes/postfixes are put in parens at the end of the line. endian
- could be
either le
(little-endian) or be
(big-endian).
Utilities
a.clone()
- clone numbera.toString(base, length)
- convert to base-string and pad with zeroesa.toNumber()
- convert to Javascript Number (limited to 53 bits)a.toJSON()
- convert to JSON compatible hex string (alias oftoString(16)
)a.toArray(endian, length)
- convert to byteArray
, and optionally zero pad to length, throwing if already exceedinga.toArrayLike(type, endian, length)
- convert to an instance oftype
, which must behave like anArray
a.toBuffer(endian, length)
- convert to Node.js Buffer (if available).length
in bytes. For compatibility with browserify and similar tools, use this instead:a.toArrayLike(Buffer, endian, length)
a.bitLength()
- get number of bits occupieda.zeroBits()
- return number of less-significant consequent zero bits (example:1010000
has 4 zero bits)a.byteLength()
- return number of bytes occupieda.isNeg()
- true if the number is negativea.isEven()
- no commentsa.isOdd()
- no commentsa.isZero()
- no commentsa.cmp(b)
- compare numbers and return-1
(a<
b),0
(a==
b), or1
(a>
b) depending on the comparison result (ucmp
,cmpn
)a.lt(b)
-a
less thanb
(n
)a.lte(b)
-a
less than or equalsb
(n
)a.gt(b)
-a
greater thanb
(n
)a.gte(b)
-a
greater than or equalsb
(n
)a.eq(b)
-a
equalsb
(n
)a.toTwos(width)
- convert to two's complement representation, wherewidth
is bit widtha.fromTwos(width)
- convert from two's complement representation, wherewidth
is the bit widthBN.isBN(object)
- returns true if the suppliedobject
is a BN.js instanceBN.max(a, b)
- returna
ifa
bigger thanb
BN.min(a, b)
- returna
ifa
less thanb
Arithmetics
a.neg()
- negate sign (i
)a.abs()
- absolute value (i
)a.add(b)
- addition (i
,n
,in
)a.sub(b)
- subtraction (i
,n
,in
)a.mul(b)
- multiply (i
,n
,in
)a.sqr()
- square (i
)a.pow(b)
- raisea
to the power ofb
a.div(b)
- divide (divn
,idivn
)a.mod(b)
- reduct (u
,n
) (but noumodn
)a.divmod(b)
- quotient and modulus obtained by dividinga.divRound(b)
- rounded division
Bit operations
a.or(b)
- or (i
,u
,iu
)a.and(b)
- and (i
,u
,iu
,andln
) (NOTE:andln
is going to be replaced withandn
in future)a.xor(b)
- xor (i
,u
,iu
)a.setn(b, value)
- set specified bit tovalue
a.shln(b)
- shift left (i
,u
,iu
)a.shrn(b)
- shift right (i
,u
,iu
)a.testn(b)
- test if specified bit is seta.maskn(b)
- clear bits with indexes higher or equal tob
(i
)a.bincn(b)
- add1 << b
to the numbera.notn(w)
- not (for the width specified byw
) (i
)
Reduction
a.gcd(b)
- GCDa.egcd(b)
- Extended GCD results ({ a: ..., b: ..., gcd: ... }
)a.invm(b)
- inversea
modulob
Fast reduction
When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like Montgomery multiplication, or using special algorithm for Mersenne Prime.
Reduction context
To enable this trick one should create a reduction context:
var red = BN.red(num);
where num
is just a BN instance.
Or:
var red = BN.red(primeName);
Where primeName
is either of these Mersenne Primes:
'k256'
'p224'
'p192'
'p25519'
Or:
var red = BN.mont(num);
To reduce numbers with Montgomery trick. .mont()
is generally faster than
.red(num)
, but slower than BN.red(primeName)
.
Converting numbers
Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should:
- Convert inputs to reducted ones
- Operate on them in reduction context
- Convert outputs back from the reduction context
Here is how one may convert numbers to red
:
var redA = a.toRed(red);
Where red
is a reduction context created using instructions above
Here is how to convert them back:
var a = redA.fromRed();
Red instructions
Most of the instructions from the very start of this readme have their counterparts in red context:
a.redAdd(b)
,a.redIAdd(b)
a.redSub(b)
,a.redISub(b)
a.redShl(num)
a.redMul(b)
,a.redIMul(b)
a.redSqr()
,a.redISqr()
a.redSqrt()
- square root modulo reduction context's primea.redInvm()
- modular inverse of the numbera.redNeg()
a.redPow(b)
- modular exponentiation
Number Size
Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers.
LICENSE
This software is licensed under the MIT License.
Top Related Projects
A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
An arbitrary length integer library for Javascript
An extensive math library for JavaScript and Node.js
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot