UNPKG

1.49 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.hexToU8a = hexToU8a;
7
8var _stripPrefix = require("./stripPrefix");
9
10// Copyright 2017-2022 @polkadot/util authors & contributors
11// SPDX-License-Identifier: Apache-2.0
12
13/**
14 * @name hexToU8a
15 * @summary Creates a Uint8Array object from a hex string.
16 * @description
17 * `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.
18 * @example
19 * <BR>
20 *
21 * ```javascript
22 * import { hexToU8a } from '@polkadot/util';
23 *
24 * hexToU8a('0x80001f'); // Uint8Array([0x80, 0x00, 0x1f])
25 * hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
26 * ```
27 */
28function hexToU8a(_value) {
29 let bitLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;
30
31 if (!_value) {
32 return new Uint8Array();
33 }
34
35 const value = (0, _stripPrefix.hexStripPrefix)(_value);
36 const buf = Buffer.from(value, 'hex');
37 const valLength = value.length / 2;
38 const resultLength = Math.ceil(bitLength === -1 ? valLength : bitLength / 8);
39
40 if (resultLength === valLength) {
41 return Uint8Array.from(buf);
42 }
43
44 const offset = resultLength > valLength ? resultLength - valLength : 0;
45
46 if (offset) {
47 const u8a = new Uint8Array(resultLength);
48 u8a.set(buf, offset);
49 return u8a;
50 }
51
52 return Uint8Array.from(buf.slice(0, resultLength));
53}
\No newline at end of file