1 | // Copyright 2017-2022 @polkadot/util authors & contributors
|
2 | // SPDX-License-Identifier: Apache-2.0
|
3 | import { hexAddPrefix } from "./addPrefix.js";
|
4 | import { hexStripPrefix } from "./stripPrefix.js";
|
5 | /**
|
6 | * @name hexFixLength
|
7 | * @summary Shifts a hex string to a specific bitLength
|
8 | * @description
|
9 | * Returns a `0x` prefixed string with the specified number of bits contained in the return value. (If bitLength is -1, length checking is not done). Values with more bits are trimmed to the specified length. Input values with less bits are returned as-is by default. When `withPadding` is set, shorter values are padded with `0`.
|
10 | * @example
|
11 | * <BR>
|
12 | *
|
13 | * ```javascript
|
14 | * import { hexFixLength } from '@polkadot/util';
|
15 | *
|
16 | * console.log('fixed', hexFixLength('0x12', 16)); // => 0x12
|
17 | * console.log('fixed', hexFixLength('0x12', 16, true)); // => 0x0012
|
18 | * console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12
|
19 | * ```
|
20 | */
|
21 |
|
22 | export function hexFixLength(value, bitLength = -1, withPadding = false) {
|
23 | const strLength = Math.ceil(bitLength / 4);
|
24 | const hexLength = strLength + 2;
|
25 | return hexAddPrefix(bitLength === -1 || value.length === hexLength || !withPadding && value.length < hexLength ? hexStripPrefix(value) : value.length > hexLength ? hexStripPrefix(value).slice(-1 * strLength) : `${'0'.repeat(strLength)}${hexStripPrefix(value)}`.slice(-1 * strLength));
|
26 | } |
\ | No newline at end of file |