0
# Long.js
1
2
Long.js is a JavaScript library for representing 64-bit two's-complement integer values, addressing JavaScript's native number limitations (safe integers only up to 2^53-1). Derived from Google Closure Library with WebAssembly optimizations for high-performance 64-bit integer operations.
3
4
## Package Information
5
6
- **Package Name**: long
7
- **Package Type**: npm
8
- **Language**: JavaScript (with TypeScript definitions)
9
- **Installation**: `npm install long`
10
11
## Core Imports
12
13
```typescript
14
import Long from "long";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const Long = require("long");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import Long from "long";
27
28
// Create Long instances
29
const a = Long.fromString("9223372036854775807");
30
const b = Long.fromNumber(1000);
31
const c = new Long(0xFFFFFFFF, 0x7FFFFFFF); // low, high bits
32
33
// Perform operations
34
const sum = a.add(b);
35
const product = a.multiply(Long.fromInt(2));
36
const quotient = a.divide(b);
37
38
// Convert back to other formats
39
console.log(sum.toString()); // "9223372036854776807"
40
console.log(product.toNumber()); // May lose precision for large values
41
console.log(quotient.toBigInt()); // 9223372036854775n
42
```
43
44
## Architecture
45
46
Long.js provides a complete 64-bit integer implementation with:
47
48
- **Immutable Operations**: All operations return new Long instances
49
- **Type Safety**: Full support for both signed and unsigned 64-bit integers
50
- **Multiple Input Formats**: Create from strings, numbers, bytes, or bit values
51
- **WebAssembly Optimizations**: Native i64 operations for multiplication and division
52
- **JavaScript Integration**: Seamless conversion to native types including BigInt
53
54
## Capabilities
55
56
### Constructor and Constants
57
58
Create Long instances and access predefined constants.
59
60
```typescript { .api }
61
/**
62
* Constructs a 64-bit two's-complement integer
63
* @param low - Lower 32 bits as signed integer
64
* @param high - Upper 32 bits as signed integer
65
* @param unsigned - Whether this represents an unsigned value
66
*/
67
constructor(low: number, high: number, unsigned?: boolean);
68
69
// Predefined constants
70
static readonly ZERO: Long; // Signed zero
71
static readonly UZERO: Long; // Unsigned zero
72
static readonly ONE: Long; // Signed one
73
static readonly UONE: Long; // Unsigned one
74
static readonly NEG_ONE: Long; // Signed negative one
75
static readonly MAX_VALUE: Long; // Maximum signed value (2^63-1)
76
static readonly MIN_VALUE: Long; // Minimum signed value (-2^63)
77
static readonly MAX_UNSIGNED_VALUE: Long; // Maximum unsigned value (2^64-1)
78
static readonly MAX_SAFE_INTEGER: Long; // Maximum safe JS integer (2^53-1)
79
static readonly MIN_SAFE_INTEGER: Long; // Minimum safe JS integer (-2^53+1)
80
```
81
82
### Static Creation Methods
83
84
Create Long instances from various input types.
85
86
```typescript { .api }
87
/**
88
* Creates a Long from a 32-bit integer
89
*/
90
static fromInt(value: number, unsigned?: boolean): Long;
91
92
/**
93
* Creates a Long from a JavaScript number
94
*/
95
static fromNumber(value: number, unsigned?: boolean): Long;
96
97
/**
98
* Creates a Long from a string representation
99
*/
100
static fromString(str: string, unsigned?: boolean, radix?: number): Long;
101
102
/**
103
* Creates a Long from a byte array
104
*/
105
static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long;
106
107
/**
108
* Creates a Long from low and high 32-bit values
109
*/
110
static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long;
111
112
/**
113
* Creates a Long from various input types
114
*/
115
static fromValue(val: Long | number | string | {low: number, high: number, unsigned?: boolean}, unsigned?: boolean): Long;
116
117
/**
118
* Creates a Long from a BigInt value
119
*/
120
static fromBigInt(value: bigint, unsigned?: boolean): Long;
121
122
/**
123
* Tests if an object is a Long instance
124
*/
125
static isLong(obj: any): obj is Long;
126
```
127
128
### Instance Properties
129
130
Access the internal representation of Long values.
131
132
```typescript { .api }
133
/** Lower 32 bits as signed integer */
134
readonly low: number;
135
136
/** Upper 32 bits as signed integer */
137
readonly high: number;
138
139
/** Whether this Long represents an unsigned value */
140
readonly unsigned: boolean;
141
```
142
143
### Arithmetic Operations
144
145
Perform mathematical operations on Long values.
146
147
```typescript { .api }
148
/**
149
* Adds another Long to this Long
150
*/
151
add(addend: Long | number | string): Long;
152
153
/**
154
* Subtracts another Long from this Long
155
*/
156
subtract(subtrahend: Long | number | string): Long;
157
158
/**
159
* Multiplies this Long by another Long
160
*/
161
multiply(multiplier: Long | number | string): Long;
162
163
/**
164
* Divides this Long by another Long
165
*/
166
divide(divisor: Long | number | string): Long;
167
168
/**
169
* Gets the remainder of division by another Long
170
*/
171
modulo(divisor: Long | number | string): Long;
172
173
/**
174
* Returns the negation of this Long
175
*/
176
negate(): Long;
177
178
/**
179
* Returns the absolute value of this Long
180
*/
181
abs(): Long;
182
```
183
184
### Bitwise Operations
185
186
Perform bitwise operations on Long values.
187
188
```typescript { .api }
189
/**
190
* Performs bitwise AND operation
191
*/
192
and(other: Long | number | string): Long;
193
194
/**
195
* Performs bitwise OR operation
196
*/
197
or(other: Long | number | string): Long;
198
199
/**
200
* Performs bitwise XOR operation
201
*/
202
xor(other: Long | number | string): Long;
203
204
/**
205
* Performs bitwise NOT operation
206
*/
207
not(): Long;
208
209
/**
210
* Shifts bits left by specified number of positions
211
*/
212
shiftLeft(numBits: number): Long;
213
214
/**
215
* Performs arithmetic right shift (sign-extending)
216
*/
217
shiftRight(numBits: number): Long;
218
219
/**
220
* Performs logical right shift (zero-filling)
221
*/
222
shiftRightUnsigned(numBits: number): Long;
223
224
/**
225
* Rotates bits left by specified number of positions
226
*/
227
rotateLeft(numBits: number): Long;
228
229
/**
230
* Rotates bits right by specified number of positions
231
*/
232
rotateRight(numBits: number): Long;
233
```
234
235
### Comparison Operations
236
237
Compare Long values with each other.
238
239
```typescript { .api }
240
/**
241
* Tests if this Long equals another Long
242
*/
243
equals(other: Long | number | string): boolean;
244
245
/**
246
* Tests if this Long does not equal another Long
247
*/
248
notEquals(other: Long | number | string): boolean;
249
250
/**
251
* Tests if this Long is less than another Long
252
*/
253
lessThan(other: Long | number | string): boolean;
254
255
/**
256
* Tests if this Long is less than or equal to another Long
257
*/
258
lessThanOrEqual(other: Long | number | string): boolean;
259
260
/**
261
* Tests if this Long is greater than another Long
262
*/
263
greaterThan(other: Long | number | string): boolean;
264
265
/**
266
* Tests if this Long is greater than or equal to another Long
267
*/
268
greaterThanOrEqual(other: Long | number | string): boolean;
269
270
/**
271
* Compares this Long with another Long
272
* @returns -1 if less than, 0 if equal, 1 if greater than
273
*/
274
compare(other: Long | number | string): number;
275
276
/**
277
* Alias for compare method
278
*/
279
comp(other: Long | number | string): number;
280
```
281
282
### Conversion Operations
283
284
Convert Long values to other formats.
285
286
```typescript { .api }
287
/**
288
* Converts to JavaScript number (may lose precision)
289
*/
290
toNumber(): number;
291
292
/**
293
* Converts to native BigInt value
294
*/
295
toBigInt(): bigint;
296
297
/**
298
* Converts to string representation
299
*/
300
toString(radix?: number): string;
301
302
/**
303
* Converts to byte array
304
*/
305
toBytes(le?: boolean): number[];
306
307
/**
308
* Converts to little-endian byte array
309
*/
310
toBytesLE(): number[];
311
312
/**
313
* Converts to big-endian byte array
314
*/
315
toBytesBE(): number[];
316
317
/**
318
* Returns numeric value (calls toNumber)
319
*/
320
valueOf(): number;
321
```
322
323
### Type and State Checking
324
325
Check properties and state of Long values.
326
327
```typescript { .api }
328
/**
329
* Tests if this Long is zero
330
*/
331
isZero(): boolean;
332
333
/**
334
* Tests if this Long is negative
335
*/
336
isNegative(): boolean;
337
338
/**
339
* Tests if this Long is positive
340
*/
341
isPositive(): boolean;
342
343
/**
344
* Tests if this Long is odd
345
*/
346
isOdd(): boolean;
347
348
/**
349
* Tests if this Long is even
350
*/
351
isEven(): boolean;
352
353
/**
354
* Tests if this Long is within safe JavaScript integer range
355
*/
356
isSafeInteger(): boolean;
357
```
358
359
### Type Conversion
360
361
Convert between signed and unsigned representations.
362
363
```typescript { .api }
364
/**
365
* Converts to signed representation
366
*/
367
toSigned(): Long;
368
369
/**
370
* Converts to unsigned representation
371
*/
372
toUnsigned(): Long;
373
```
374
375
## Error Handling
376
377
Long.js throws errors in the following cases:
378
379
- **Division by zero**: `divide()` and `modulo()` methods throw `RangeError` when divisor is zero
380
- **Invalid string parsing**: `fromString()` throws `Error` for invalid string representations
381
- **Overflow conditions**: Handled according to 64-bit two's complement arithmetic rules with wrapping
382
383
## WebAssembly Integration
384
385
Long.js includes WebAssembly optimizations for enhanced performance:
386
387
- **Multiplication operations**: Uses native i64 multiplication when available
388
- **Division operations**: Uses native i64 division for both signed and unsigned operations
389
- **Remainder operations**: Uses native i64 remainder calculation for optimal performance
390
391
## Usage Examples
392
393
**Working with large integers:**
394
395
```typescript
396
// Cryptocurrency calculations
397
const satoshis = Long.fromString("2100000000000000"); // Max Bitcoin supply in satoshis
398
const btcPrice = Long.fromNumber(50000);
399
const totalValue = satoshis.multiply(btcPrice);
400
401
// Database ID management
402
const userId = Long.fromString("18446744073709551615"); // Max uint64
403
const isValidId = userId.lessThan(Long.MAX_UNSIGNED_VALUE);
404
405
// Timestamp operations
406
const timestamp = Long.fromNumber(Date.now()).multiply(1000000); // Convert to nanoseconds
407
const futureTime = timestamp.add(Long.fromNumber(86400000000000)); // Add 1 day in nanoseconds
408
```
409
410
**Bitwise operations for flags:**
411
412
```typescript
413
const FLAGS = {
414
READ: Long.fromInt(1), // 0001
415
WRITE: Long.fromInt(2), // 0010
416
EXECUTE: Long.fromInt(4), // 0100
417
ADMIN: Long.fromInt(8) // 1000
418
};
419
420
let permissions = Long.ZERO;
421
permissions = permissions.or(FLAGS.READ).or(FLAGS.WRITE);
422
423
const canRead = permissions.and(FLAGS.READ).notEquals(Long.ZERO);
424
const canExecute = permissions.and(FLAGS.EXECUTE).notEquals(Long.ZERO);
425
```