0
# Big Number Operations
1
2
Support for both native BigInt and BN.js big numbers with utility functions, constants, and conversion methods for high-precision arithmetic operations in blockchain applications.
3
4
## Capabilities
5
6
### BigInt Utilities
7
8
Native JavaScript BigInt operations with utility functions for common mathematical operations.
9
10
```typescript { .api }
11
/**
12
* Converts number to BigInt
13
* @param value - Number, bigint, or string to convert
14
*/
15
function nToBigInt(value: number | bigint | string): bigint;
16
17
/**
18
* Converts BigInt to hex string
19
* @param value - BigInt to convert
20
* @param bitLength - Expected bit length for padding
21
*/
22
function nToHex(value: bigint, bitLength?: number): HexString;
23
24
/**
25
* Converts BigInt to Uint8Array
26
* @param value - BigInt to convert
27
* @param bitLength - Expected bit length in bits
28
*/
29
function nToU8a(value: bigint, bitLength?: number): Uint8Array;
30
31
/**
32
* Returns maximum of BigInt values
33
* @param values - BigInt values to compare
34
*/
35
function nMax(...values: bigint[]): bigint;
36
37
/**
38
* Returns minimum of BigInt values
39
* @param values - BigInt values to compare
40
*/
41
function nMin(...values: bigint[]): bigint;
42
43
/**
44
* Calculates square root of BigInt value
45
* @param value - BigInt to calculate square root of
46
*/
47
function nSqrt(value: bigint): bigint;
48
```
49
50
### BigInt Constants
51
52
Pre-defined BigInt constants for common values to avoid repeated conversions.
53
54
```typescript { .api }
55
const _0n: bigint; // 0n
56
const _1n: bigint; // 1n
57
const _2n: bigint; // 2n
58
const _3n: bigint; // 3n
59
const _4n: bigint; // 4n
60
const _5n: bigint; // 5n
61
const _6n: bigint; // 6n
62
const _7n: bigint; // 7n
63
const _8n: bigint; // 8n
64
const _9n: bigint; // 9n
65
const _10n: bigint; // 10n
66
const _100n: bigint; // 100n
67
const _1000n: bigint; // 1000n
68
const _1Mn: bigint; // 1,000,000n (million)
69
const _1Bn: bigint; // 1,000,000,000n (billion)
70
const _1Qn: bigint; // 1,000,000,000,000,000,000n (quintillion)
71
const _2pow53n: bigint; // MAX_SAFE_INTEGER as BigInt
72
const _sqrt2pow53n: bigint; // Math.sqrt(MAX_SAFE_INTEGER) as BigInt
73
```
74
75
### BN.js Utilities
76
77
BN.js big number operations for compatibility with existing blockchain libraries.
78
79
```typescript { .api }
80
/**
81
* Converts value to BN (big number)
82
* @param value - Value to convert (number, string, bigint, Uint8Array, BN)
83
*/
84
function bnToBn(value: BN | number | string | bigint | Uint8Array): BN;
85
86
/**
87
* Creates BN from hex string
88
* @param value - Hex string to convert
89
*/
90
function bnFromHex(value: string): BN;
91
92
/**
93
* Converts BN to hex string
94
* @param value - BN to convert
95
* @param bitLength - Expected bit length for padding
96
*/
97
function bnToHex(value: BN, bitLength?: number): HexString;
98
99
/**
100
* Converts BN to Uint8Array
101
* @param value - BN to convert
102
* @param options - Conversion options (endianness, sign)
103
*/
104
function bnToU8a(value: BN, options?: ToBnOptions): Uint8Array;
105
106
/**
107
* Returns maximum of BN values
108
* @param values - BN values to compare
109
*/
110
function bnMax(...values: BN[]): BN;
111
112
/**
113
* Returns minimum of BN values
114
* @param values - BN values to compare
115
*/
116
function bnMin(...values: BN[]): BN;
117
118
/**
119
* Calculates square root of BN value
120
* @param value - BN to calculate square root of
121
*/
122
function bnSqrt(value: BN): BN;
123
```
124
125
### BN Class
126
127
The BN class provides comprehensive big number arithmetic operations.
128
129
```typescript { .api }
130
class BN {
131
/**
132
* Creates a new BN instance
133
* @param number - Number, string, number array, Uint8Array, Buffer, or BN
134
* @param base - Base for parsing (default 10, or 'hex')
135
* @param endian - Endianness for array inputs ('le' or 'be')
136
*/
137
constructor(number: number | string | number[] | Uint8Array | Buffer | BN, base?: number | 'hex', endian?: 'le' | 'be');
138
139
// Arithmetic operations
140
add(b: BN): BN;
141
sub(b: BN): BN;
142
mul(b: BN): BN;
143
div(b: BN): BN;
144
mod(b: BN): BN;
145
pow(b: BN): BN;
146
sqrt(): BN;
147
148
// Comparison operations
149
eq(b: BN): boolean;
150
lt(b: BN): boolean;
151
lte(b: BN): boolean;
152
gt(b: BN): boolean;
153
gte(b: BN): boolean;
154
cmp(b: BN): -1 | 0 | 1;
155
156
// Bitwise operations
157
and(b: BN): BN;
158
or(b: BN): BN;
159
xor(b: BN): BN;
160
shln(b: number): BN;
161
shrn(b: number): BN;
162
163
// Conversion methods
164
toString(base?: number | 'hex', length?: number): string;
165
toNumber(): number;
166
toArray(endian?: 'le' | 'be', length?: number): number[];
167
toBuffer(endian?: 'le' | 'be', length?: number): Buffer;
168
169
// Utility methods
170
isZero(): boolean;
171
isNeg(): boolean;
172
clone(): BN;
173
neg(): BN;
174
abs(): BN;
175
}
176
```
177
178
### BN Constants
179
180
Pre-defined BN constants for common values.
181
182
```typescript { .api }
183
const BN_ZERO: BN; // BN(0)
184
const BN_ONE: BN; // BN(1)
185
const BN_TWO: BN; // BN(2)
186
const BN_THREE: BN; // BN(3)
187
const BN_FOUR: BN; // BN(4)
188
const BN_FIVE: BN; // BN(5)
189
const BN_SIX: BN; // BN(6)
190
const BN_SEVEN: BN; // BN(7)
191
const BN_EIGHT: BN; // BN(8)
192
const BN_NINE: BN; // BN(9)
193
const BN_TEN: BN; // BN(10)
194
const BN_HUNDRED: BN; // BN(100)
195
const BN_THOUSAND: BN; // BN(1000)
196
const BN_MILLION: BN; // BN(1000000)
197
const BN_BILLION: BN; // BN(1000000000)
198
const BN_QUINTILL: BN; // BN(1000000000000000000)
199
const BN_MAX_INTEGER: BN; // BN(Number.MAX_SAFE_INTEGER)
200
const BN_SQRT_MAX_INTEGER: BN; // BN(Math.sqrt(Number.MAX_SAFE_INTEGER))
201
```
202
203
## Usage Examples
204
205
**BigInt Operations:**
206
207
```typescript
208
import {
209
nToBigInt, nToHex, nMax, nMin, nSqrt,
210
_1Mn, _1Bn, _2pow53n
211
} from "@polkadot/util";
212
213
// Convert to BigInt
214
const value = nToBigInt("123456789012345678901234567890");
215
console.log(value); // 123456789012345678901234567890n
216
217
// Mathematical operations
218
const max = nMax(_1Mn, _1Bn, value); // Returns largest value
219
const min = nMin(_1Mn, _1Bn, value); // Returns smallest value
220
const sqrt = nSqrt(_1Bn); // Square root of 1 billion
221
222
// Convert to hex
223
const hex = nToHex(value, 256); // Hex with 256-bit padding
224
225
// Use constants
226
const largeValue = _2pow53n * _1Mn; // Very large calculation
227
```
228
229
**BN.js Operations:**
230
231
```typescript
232
import {
233
BN, bnToBn, bnFromHex, bnToHex,
234
BN_ZERO, BN_ONE, BN_MILLION
235
} from "@polkadot/util";
236
237
// Create BN instances
238
const bn1 = bnToBn("1000000000000000000000"); // From string
239
const bn2 = bnFromHex("0x1000000000000000000"); // From hex
240
const bn3 = new BN(123456789); // Direct constructor
241
242
// Arithmetic operations
243
const sum = bn1.add(bn2);
244
const difference = bn1.sub(bn2);
245
const product = bn1.mul(BN_MILLION);
246
const quotient = bn1.div(BN_ONE);
247
248
// Comparisons
249
if (sum.gt(BN_ZERO)) {
250
console.log("Sum is positive");
251
}
252
253
// Convert back to different formats
254
const hex = bnToHex(sum); // To hex string
255
const str = sum.toString(); // To decimal string
256
const num = sum.toNumber(); // To number (if within safe range)
257
```
258
259
**Balance Calculations:**
260
261
```typescript
262
import { BN, bnToBn, BN_MILLION } from "@polkadot/util";
263
264
// Calculate token amounts (assuming 12 decimals)
265
const DECIMALS = new BN(10).pow(new BN(12));
266
267
function toTokens(amount: string | number): BN {
268
return bnToBn(amount).mul(DECIMALS);
269
}
270
271
function fromTokens(amount: BN): string {
272
return amount.div(DECIMALS).toString();
273
}
274
275
// Usage
276
const userBalance = toTokens("100.5"); // 100.5 tokens in smallest units
277
const fee = toTokens("0.01"); // 0.01 tokens as fee
278
const remaining = userBalance.sub(fee);
279
280
console.log(`Remaining: ${fromTokens(remaining)} tokens`);
281
```
282
283
**Working with Both BigInt and BN:**
284
285
```typescript
286
import { nToBigInt, bnToBn, BN } from "@polkadot/util";
287
288
function convertBetweenTypes(value: string) {
289
// As BigInt (native)
290
const asBigInt = nToBigInt(value);
291
292
// As BN (library)
293
const asBN = bnToBn(value);
294
295
// Convert BN to BigInt
296
const bnToBigInt = BigInt(asBN.toString());
297
298
// Convert BigInt to BN
299
const bigIntToBN = new BN(asBigInt.toString());
300
301
return { asBigInt, asBN, bnToBigInt, bigIntToBN };
302
}
303
```
304
305
## Types
306
307
```typescript { .api }
308
interface ToBnOptions {
309
isLe?: boolean; // Little-endian byte order
310
isNegative?: boolean; // Handle as negative number
311
}
312
313
type HexString = `0x${string}`;
314
```