UNPKG

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