UNPKG

1.57 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { isNumber } from "../is/number.js";
4import { objectSpread } from "../object/spread.js";
5import { bnToBn } from "./toBn.js";
6const DEFAULT_OPTS = {
7 bitLength: -1,
8 isLe: true,
9 isNegative: false
10};
11/**
12 * @name bnToU8a
13 * @summary Creates a Uint8Array object from a BN.
14 * @description
15 * `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.
16 * @example
17 * <BR>
18 *
19 * ```javascript
20 * import { bnToU8a } from '@polkadot/util';
21 *
22 * bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
23 * ```
24 */
25
26/** @deprecated Use bnToU8a(value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions) */
27function bnToU8a(value, arg1 = DEFAULT_OPTS, arg2) {
28 const {
29 bitLength,
30 isLe,
31 isNegative
32 } = objectSpread({
33 bitLength: -1,
34 isLe: true,
35 isNegative: false
36 }, isNumber(arg1) ? {
37 bitLength: arg1,
38 isLe: arg2
39 } : arg1);
40 const valueBn = bnToBn(value);
41 const byteLength = bitLength === -1 ? Math.ceil(valueBn.bitLength() / 8) : Math.ceil((bitLength || 0) / 8);
42
43 if (!value) {
44 return bitLength === -1 ? new Uint8Array() : new Uint8Array(byteLength);
45 }
46
47 const output = new Uint8Array(byteLength);
48 const bn = isNegative ? valueBn.toTwos(byteLength * 8) : valueBn;
49 output.set(bn.toArray(isLe ? 'le' : 'be', byteLength), 0);
50 return output;
51}
52
53export { bnToU8a };
\No newline at end of file