1 | import { bnToBn } from './toBn.js';
|
2 | const DEFAULT_OPTS = { bitLength: -1, isLe: true, isNegative: false };
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | export function bnToU8a(value, { bitLength = -1, isLe = true, isNegative = false } = DEFAULT_OPTS) {
|
18 | const valueBn = bnToBn(value);
|
19 | const byteLength = bitLength === -1
|
20 | ? Math.ceil(valueBn.bitLength() / 8)
|
21 | : Math.ceil((bitLength || 0) / 8);
|
22 | if (!value) {
|
23 | return bitLength === -1
|
24 | ? new Uint8Array(1)
|
25 | : new Uint8Array(byteLength);
|
26 | }
|
27 | const output = new Uint8Array(byteLength);
|
28 | const bn = isNegative
|
29 | ? valueBn.toTwos(byteLength * 8)
|
30 | : valueBn;
|
31 | output.set(bn.toArray(isLe ? 'le' : 'be', byteLength), 0);
|
32 | return output;
|
33 | }
|