UNPKG

1.03 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3
4/**
5 * @name u8aFixLength
6 * @summary Shifts a Uint8Array to a specific bitLength
7 * @description
8 * Returns a uint8Array 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.
9 * @example
10 * <BR>
11 *
12 * ```javascript
13 * import { u8aFixLength } from '@polkadot/util';
14 *
15 * u8aFixLength('0x12') // => 0x12
16 * u8aFixLength('0x12', 16) // => 0x0012
17 * u8aFixLength('0x1234', 8) // => 0x12
18 * ```
19 */
20export function u8aFixLength(value, bitLength = -1, atStart = false) {
21 const byteLength = Math.ceil(bitLength / 8);
22
23 if (bitLength === -1 || value.length === byteLength) {
24 return value;
25 } else if (value.length > byteLength) {
26 return value.subarray(0, byteLength);
27 }
28
29 const result = new Uint8Array(byteLength);
30 result.set(value, atStart ? 0 : byteLength - value.length);
31 return result;
32}
\No newline at end of file