1 |
|
2 |
|
3 |
|
4 |
|
5 | export function u8aToNumber(value, { isLe = true, isNegative = false } = {}) {
|
6 |
|
7 |
|
8 | if (!isLe) {
|
9 | value = value.slice().reverse();
|
10 | }
|
11 | const count = value.length;
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | if (isNegative && count && (value[count - 1] & 0x80)) {
|
17 | switch (count) {
|
18 | case 0:
|
19 | return 0;
|
20 | case 1:
|
21 | return (((value[0] ^ 255) * -1) - 1);
|
22 | case 2:
|
23 | return ((((value[0] + (value[1] << 8)) ^ 65535) * -1) - 1);
|
24 | case 3:
|
25 | return ((((value[0] + (value[1] << 8) + (value[2] << 16)) ^ 16777215) * -1) - 1);
|
26 | case 4:
|
27 |
|
28 |
|
29 | return ((((value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 16777216)) ^ 4294967295) * -1) - 1);
|
30 | case 5:
|
31 | return (((((value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 16777216)) ^ 4294967295) + ((value[4] ^ 0xff) * 4294967296)) * -1) - 1);
|
32 | case 6:
|
33 | return (((((value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 16777216)) ^ 4294967295) + (((value[4] + (value[5] << 8)) ^ 65535) * 4294967296)) * -1) - 1);
|
34 | default:
|
35 | throw new Error('Value more than 48-bits cannot be reliably converted');
|
36 | }
|
37 | }
|
38 | switch (count) {
|
39 | case 0:
|
40 | return 0;
|
41 | case 1:
|
42 | return value[0];
|
43 | case 2:
|
44 | return value[0] + (value[1] << 8);
|
45 | case 3:
|
46 | return value[0] + (value[1] << 8) + (value[2] << 16);
|
47 | case 4:
|
48 |
|
49 |
|
50 | return value[0] + (value[1] << 8) + (value[2] << 16) + (value[3] * 16777216);
|
51 | case 5:
|
52 | return value[0] + (value[1] << 8) + (value[2] << 16) + ((value[3] + (value[4] << 8)) * 16777216);
|
53 | case 6:
|
54 | return value[0] + (value[1] << 8) + (value[2] << 16) + ((value[3] + (value[4] << 8) + (value[5] << 16)) * 16777216);
|
55 | default:
|
56 | throw new Error('Value more than 48-bits cannot be reliably converted');
|
57 | }
|
58 | }
|