1 |
|
2 |
|
3 | import { HEX_TO_U8, HEX_TO_U16 } from "./alphabet.js";
|
4 | import { hexStripPrefix } from "./stripPrefix.js";
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | export function hexToU8a(_value, bitLength = -1) {
|
22 | if (!_value) {
|
23 | return new Uint8Array();
|
24 | }
|
25 |
|
26 | const value = hexStripPrefix(_value).toLowerCase();
|
27 | const valLength = value.length / 2;
|
28 | const endLength = Math.ceil(bitLength === -1 ? valLength : bitLength / 8);
|
29 | const result = new Uint8Array(endLength);
|
30 | const offset = endLength > valLength ? endLength - valLength : 0;
|
31 | const dv = new DataView(result.buffer, offset);
|
32 | const mod = (endLength - offset) % 2;
|
33 | const length = endLength - offset - mod;
|
34 |
|
35 | for (let i = 0; i < length; i += 2) {
|
36 | const idx = i * 2;
|
37 | dv.setUint16(i, HEX_TO_U16[value.substring(idx, idx + 4)]);
|
38 | }
|
39 |
|
40 | if (mod) {
|
41 | dv.setUint8(length, HEX_TO_U8[value.substring(value.length - 2)]);
|
42 | }
|
43 |
|
44 | return result;
|
45 | } |
\ | No newline at end of file |