1 | // Copyright 2017-2022 @polkadot/util authors & contributors
|
2 | // SPDX-License-Identifier: Apache-2.0
|
3 | import { hexFixLength } from "../hex/fixLength.js";
|
4 | import { isNull } from "../is/null.js";
|
5 | import { isUndefined } from "../is/undefined.js";
|
6 | /**
|
7 | * @name numberToHex
|
8 | * @summary Creates a hex value from a number.
|
9 | * @description
|
10 | * `null`/`undefined`/`NaN` inputs returns an empty `0x` result. `number` input values return the actual bytes value converted to a `hex`. With `bitLength` set, it converts the number to the equivalent size.
|
11 | * @example
|
12 | * <BR>
|
13 | *
|
14 | * ```javascript
|
15 | * import { numberToHex } from '@polkadot/util';
|
16 | *
|
17 | * numberToHex(0x1234); // => '0x1234'
|
18 | * numberToHex(0x1234, 32); // => 0x00001234
|
19 | * ```
|
20 | */
|
21 |
|
22 | export function numberToHex(value, bitLength = -1) {
|
23 | if (isUndefined(value) || isNull(value) || isNaN(value)) {
|
24 | return '0x';
|
25 | }
|
26 |
|
27 | const hex = value.toString(16);
|
28 | return hexFixLength(hex.length % 2 ? `0${hex}` : hex, bitLength, true);
|
29 | } |
\ | No newline at end of file |