1 | import { BN } from '../bn/bn.js';
|
2 | import { hexStripPrefix } from './stripPrefix.js';
|
3 | /**
|
4 | * @name hexToBn
|
5 | * @summary Creates a BN.js object from a hex string.
|
6 | * @description
|
7 | * `null` inputs returns a `BN(0)` result. Hex input values return the actual value converted to a BN. Anything that is not a hex string (including the `0x` prefix) throws an error.
|
8 | * @param _value The value to convert
|
9 | * @param _options Options to pass while converting
|
10 | * @param _options.isLe Convert using Little Endian
|
11 | * @param _options.isNegative Convert using two's complement
|
12 | * @example
|
13 | * <BR>
|
14 | *
|
15 | * ```javascript
|
16 | * import { hexToBn } from '@polkadot/util';
|
17 | *
|
18 | * hexToBn('0x123480001f'); // => BN(0x123480001f)
|
19 | * ```
|
20 | */
|
21 | export function hexToBn(value, { isLe = false, isNegative = false } = {}) {
|
22 | if (!value || value === '0x') {
|
23 | return new BN(0);
|
24 | }
|
25 | const stripped = hexStripPrefix(value);
|
26 | const bn = new BN(stripped, 16, isLe ? 'le' : 'be');
|
27 | // fromTwos takes as parameter the number of bits, which is the hex length
|
28 | // multiplied by 4 (2 bytes being 8 bits)
|
29 | return isNegative
|
30 | ? bn.fromTwos(stripped.length * 4)
|
31 | : bn;
|
32 | }
|