UNPKG

1.31 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.bnToU8a = void 0;
4const toBn_js_1 = require("./toBn.js");
5const DEFAULT_OPTS = { bitLength: -1, isLe: true, isNegative: false };
6/**
7 * @name bnToU8a
8 * @summary Creates a Uint8Array object from a BN.
9 * @description
10 * `null`/`undefined`/`NaN` inputs returns an empty `Uint8Array` result. `BN` input values return the actual bytes value converted to a `Uint8Array`. Optionally convert using little-endian format if `isLE` is set.
11 * @example
12 * <BR>
13 *
14 * ```javascript
15 * import { bnToU8a } from '@polkadot/util';
16 *
17 * bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
18 * ```
19 */
20function bnToU8a(value, { bitLength = -1, isLe = true, isNegative = false } = DEFAULT_OPTS) {
21 const valueBn = (0, toBn_js_1.bnToBn)(value);
22 const byteLength = bitLength === -1
23 ? Math.ceil(valueBn.bitLength() / 8)
24 : Math.ceil((bitLength || 0) / 8);
25 if (!value) {
26 return bitLength === -1
27 ? new Uint8Array(1)
28 : new Uint8Array(byteLength);
29 }
30 const output = new Uint8Array(byteLength);
31 const bn = isNegative
32 ? valueBn.toTwos(byteLength * 8)
33 : valueBn;
34 output.set(bn.toArray(isLe ? 'le' : 'be', byteLength), 0);
35 return output;
36}
37exports.bnToU8a = bnToU8a;