UNPKG

1.86 kBJavaScriptView Raw
1const CHR = '0123456789abcdef';
2const U8 = new Uint8Array(256);
3const U16 = new Uint8Array(256 * 256);
4for (let i = 0; i < CHR.length; i++) {
5 U8[CHR[i].charCodeAt(0) | 0] = i | 0;
6 if (i > 9) {
7 U8[CHR[i].toUpperCase().charCodeAt(0) | 0] = i | 0;
8 }
9}
10for (let i = 0; i < 256; i++) {
11 const s = i << 8;
12 for (let j = 0; j < 256; j++) {
13 U16[s | j] = (U8[i] << 4) | U8[j];
14 }
15}
16/**
17 * @name hexToU8a
18 * @summary Creates a Uint8Array object from a hex string.
19 * @description
20 * `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.
21 * @example
22 * <BR>
23 *
24 * ```javascript
25 * import { hexToU8a } from '@polkadot/util';
26 *
27 * hexToU8a('0x80001f'); // Uint8Array([0x80, 0x00, 0x1f])
28 * hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
29 * ```
30 */
31export function hexToU8a(value, bitLength = -1) {
32 if (!value) {
33 return new Uint8Array();
34 }
35 let s = value.startsWith('0x')
36 ? 2
37 : 0;
38 const decLength = Math.ceil((value.length - s) / 2);
39 const endLength = Math.ceil(bitLength === -1
40 ? decLength
41 : bitLength / 8);
42 const result = new Uint8Array(endLength);
43 const offset = endLength > decLength
44 ? endLength - decLength
45 : 0;
46 for (let i = offset; i < endLength; i++, s += 2) {
47 // The big factor here is actually the string lookups. If we do
48 // HEX_TO_U16[value.substring()] we get an 10x slowdown. In the
49 // same vein using charCodeAt (as opposed to value[s] or value.charAt(s)) is
50 // also the faster operation by at least 2x with the character map above
51 result[i] = U16[(value.charCodeAt(s) << 8) | value.charCodeAt(s + 1)];
52 }
53 return result;
54}
\No newline at end of file