UNPKG

740 BJavaScriptView Raw
1import { hexFixLength } from '../hex/fixLength.js';
2/**
3 * @name numberToHex
4 * @summary Creates a hex value from a number.
5 * @description
6 * `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.
7 * @example
8 * <BR>
9 *
10 * ```javascript
11 * import { numberToHex } from '@polkadot/util';
12 *
13 * numberToHex(0x1234); // => '0x1234'
14 * numberToHex(0x1234, 32); // => 0x00001234
15 * ```
16 */
17export function numberToHex(value, bitLength = -1) {
18 const hex = (!value || Number.isNaN(value) ? 0 : value).toString(16);
19 return hexFixLength(hex.length % 2 ? `0${hex}` : hex, bitLength, true);
20}