UNPKG

1.5 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { HEX_TO_U8, HEX_TO_U16 } from "./alphabet.js";
4import { hexStripPrefix } from "./stripPrefix.js";
5/**
6 * @name hexToU8a
7 * @summary Creates a Uint8Array object from a hex string.
8 * @description
9 * `null` inputs returns an empty `Uint8Array` result. Hex input values return the actual bytes value converted to a Uint8Array. Anything that is not a hex string (including the `0x` prefix) throws an error.
10 * @example
11 * <BR>
12 *
13 * ```javascript
14 * import { hexToU8a } from '@polkadot/util';
15 *
16 * hexToU8a('0x80001f'); // Uint8Array([0x80, 0x00, 0x1f])
17 * hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
18 * ```
19 */
20
21export function hexToU8a(_value, bitLength = -1) {
22 if (!_value) {
23 return new Uint8Array();
24 }
25
26 const value = hexStripPrefix(_value).toLowerCase();
27 const valLength = value.length / 2;
28 const endLength = Math.ceil(bitLength === -1 ? valLength : bitLength / 8);
29 const result = new Uint8Array(endLength);
30 const offset = endLength > valLength ? endLength - valLength : 0;
31 const dv = new DataView(result.buffer, offset);
32 const mod = (endLength - offset) % 2;
33 const length = endLength - offset - mod;
34
35 for (let i = 0; i < length; i += 2) {
36 const idx = i * 2;
37 dv.setUint16(i, HEX_TO_U16[value.substring(idx, idx + 4)]);
38 }
39
40 if (mod) {
41 dv.setUint8(length, HEX_TO_U8[value.substring(value.length - 2)]);
42 }
43
44 return result;
45}
\No newline at end of file