-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
121 lines (97 loc) · 2.16 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
function ascii_decoder(byte_array)
{
let output = "";
for (let i = 0; i < byte_array.length; i++)
{
if (byte_array[i] == 0x00)
break;
output += String.fromCharCode(byte_array[i]);
}
return output;
}
function ascii_encoder(s)
{
let output = [];
for (let i = 0; i < 5; i++)
{
if (i < s.length)
output.push(s[i].charCodeAt());
else
output.push(0x00);
}
return output;
}
function from_little_endian_s(byte_array)
{
let output = 0;
for (let i = byte_array.length - 1; i >= 0; i--)
output |= byte_array[i] << i * 8;
if (byte_array[0] & 0x80)
{
output = logical_not(output, byte_array.length);
output++;
output *= -1;
}
return output;
}
function from_little_endian_u(byte_array)
{
let output = 0;
for (let i = byte_array.length - 1; i >= 0; i--)
output |= byte_array[i] << i * 8;
return output;
}
function to_little_endian_s(n, bytes)
{
let output = [];
let k = byte_safety_s(n, bytes);
let l;
if (k < 0)
l = 2 ** (8 * bytes) + k;
else
l = k;
for (let i = 0; i < bytes; i++)
output.push((l & (0xff << i * 8)) >> i * 8);
return output;
}
function to_little_endian_u(n, bytes)
{
let output = [];
let k = byte_safety_u(n, bytes);
for (let i = 0; i < bytes; i++)
output.push((k & (0xff << i * 8)) >> i * 8);
return output;
}
function byte_safety_s(n, bytes)
{
if (n < -(2 ** (8 * bytes - 1)))
return -(2 ** (8 * bytes - 1));
else if (n > 2 ** (8 * bytes - 1) - 1)
return 2 ** (8 * bytes - 1) - 1;
return n;
}
function byte_safety_u(n, bytes)
{
if (n < 0)
return 0;
else if (n > 2 ** (bytes * 8) - 1)
return 2 ** (bytes * 8) - 1;
return n;
}
function logical_not(n, bytes) {
if (n > 2 ** (bytes * 8) - 1)
return 0;
else if (n < 0)
return 0;
let result = 0;
let mask;
for (let i = 0; i < bytes * 8; i++)
{
mask = n & (0b1 << i);
if (!mask)
{
result = result | (0b1 << i);
}
}
return result;
}