UNPKG

1.36 kBJavaScriptView Raw
1import { BigInt } from '@polkadot/x-bigint';
2import { _0n, _1n } from './consts.js';
3import { nToBigInt } from './toBigInt.js';
4const DIV = BigInt(256);
5const NEG_MASK = BigInt(0xff);
6function toU8a(value, isLe, isNegative) {
7 const arr = [];
8 if (isNegative) {
9 value = (value + _1n) * -_1n;
10 }
11 while (value !== _0n) {
12 const mod = value % DIV;
13 const val = Number(isNegative
14 ? mod ^ NEG_MASK
15 : mod);
16 if (isLe) {
17 arr.push(val);
18 }
19 else {
20 arr.unshift(val);
21 }
22 value = (value - mod) / DIV;
23 }
24 return Uint8Array.from(arr);
25}
26/**
27 * @name nToU8a
28 * @summary Creates a Uint8Array object from a bigint.
29 */
30export function nToU8a(value, { bitLength = -1, isLe = true, isNegative = false } = {}) {
31 const valueBi = nToBigInt(value);
32 if (valueBi === _0n) {
33 return bitLength === -1
34 ? new Uint8Array(1)
35 : new Uint8Array(Math.ceil((bitLength || 0) / 8));
36 }
37 const u8a = toU8a(valueBi, isLe, isNegative);
38 if (bitLength === -1) {
39 return u8a;
40 }
41 const byteLength = Math.ceil((bitLength || 0) / 8);
42 const output = new Uint8Array(byteLength);
43 if (isNegative) {
44 output.fill(0xff);
45 }
46 output.set(u8a, isLe ? 0 : byteLength - u8a.length);
47 return output;
48}
\No newline at end of file