UNPKG

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