UNPKG

1.4 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.hexToU8a = void 0;
4/**
5 * @name hexToU8a
6 * @summary Creates a Uint8Array object from a hex string.
7 * @description
8 * `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.
9 * @example
10 * <BR>
11 *
12 * ```javascript
13 * import { hexToU8a } from '@polkadot/util';
14 *
15 * hexToU8a('0x80001f'); // Uint8Array([0x80, 0x00, 0x1f])
16 * hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
17 * ```
18 */
19function hexToU8a(_value, bitLength = -1) {
20 if (!_value) {
21 return new Uint8Array();
22 }
23 const value = _value.startsWith('0x')
24 ? _value.substring(2)
25 : _value;
26 const buf = Buffer.from(value, 'hex');
27 const valLength = value.length / 2;
28 const resultLength = Math.ceil(bitLength === -1
29 ? valLength
30 : bitLength / 8);
31 if (resultLength === valLength) {
32 return Uint8Array.from(buf);
33 }
34 const offset = resultLength > valLength
35 ? resultLength - valLength
36 : 0;
37 if (offset) {
38 const u8a = new Uint8Array(resultLength);
39 u8a.set(buf, offset);
40 return u8a;
41 }
42 return Uint8Array.from(buf.subarray(0, resultLength));
43}
44exports.hexToU8a = hexToU8a;