UNPKG

1.17 kBJavaScriptView Raw
1import { bnToBn } from './toBn.js';
2const DEFAULT_OPTS = { bitLength: -1, isLe: true, isNegative: false };
3/**
4 * @name bnToU8a
5 * @summary Creates a Uint8Array object from a BN.
6 * @description
7 * `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.
8 * @example
9 * <BR>
10 *
11 * ```javascript
12 * import { bnToU8a } from '@polkadot/util';
13 *
14 * bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
15 * ```
16 */
17export 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}