1 | // Copyright 2017-2022 @polkadot/util authors & contributors
|
2 | // SPDX-License-Identifier: Apache-2.0
|
3 | import { BN } from "../bn/bn.js";
|
4 | import { isBoolean } from "../is/boolean.js";
|
5 | import { objectSpread } from "../object/spread.js";
|
6 | import { hexStripPrefix } from "./stripPrefix.js";
|
7 | /**
|
8 | * @name hexToBn
|
9 | * @summary Creates a BN.js object from a hex string.
|
10 | * @description
|
11 | * `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.
|
12 | * @param _value The value to convert
|
13 | * @param _options Options to pass while converting
|
14 | * @param _options.isLe Convert using Little Endian
|
15 | * @param _options.isNegative Convert using two's complement
|
16 | * @example
|
17 | * <BR>
|
18 | *
|
19 | * ```javascript
|
20 | * import { hexToBn } from '@polkadot/util';
|
21 | *
|
22 | * hexToBn('0x123480001f'); // => BN(0x123480001f)
|
23 | * ```
|
24 | */
|
25 |
|
26 | /** @deprecated Use hexToBn (value?: string | null, options?: ToBnOptions) */
|
27 | function hexToBn(value, options = {}) {
|
28 | if (!value || value === '0x') {
|
29 | return new BN(0);
|
30 | } // For hex, default to BE
|
31 |
|
32 |
|
33 | const {
|
34 | isLe,
|
35 | isNegative
|
36 | } = objectSpread({
|
37 | isLe: false,
|
38 | isNegative: false
|
39 | }, isBoolean(options) ? {
|
40 | isLe: options
|
41 | } : options);
|
42 | const stripped = hexStripPrefix(value);
|
43 | const bn = new BN(stripped, 16, isLe ? 'le' : 'be'); // fromTwos takes as parameter the number of bits, which is the hex length
|
44 | // multiplied by 4 (2 bytes being 8 bits)
|
45 |
|
46 | return isNegative ? bn.fromTwos(stripped.length * 4) : bn;
|
47 | }
|
48 |
|
49 | export { hexToBn }; |
\ | No newline at end of file |