-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtils.cs
105 lines (82 loc) · 2.69 KB
/
Utils.cs
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
using System.Text;
using Instruction = vm.Instruction;
class Utils
{
public static int ToUint32(byte[] arr)
{
if (BitConverter.IsLittleEndian)
Array.Reverse(arr);
return (int)BitConverter.ToUInt32(arr, 0);
}
public static byte[] ToByteArray(string str)
{
int nbr = int.Parse(str);
byte[] nbrArray = BitConverter.GetBytes(nbr);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(nbrArray);
}
return nbrArray;
}
public static List<string> ByteCodeToMnemonics(byte[] bytecode)
{
List<string> mnemonic = [];
int length = bytecode.Length;
int i = 0;
while (i < length)
{
if (bytecode[i] == 0 || bytecode[i] == 24)
{
mnemonic.Add($"{i}: {Instruction.vInstruction.FirstOrDefault(x => x.Value == bytecode[i]).Key} {ToUint32(bytecode[i..(i + 5)])}");
i += 5;
continue;
}
else if (bytecode[i] == 27)
{
int len = ToUint32(bytecode[i..(i + 5)]);
mnemonic.Add($"{i}: {Instruction.vInstruction.FirstOrDefault(x => x.Value == bytecode[i]).Key} {ToUint32(bytecode[i..(i + len)])}");
i += len + 5;
}
mnemonic.Add($"{i}: {Instruction.vInstruction.FirstOrDefault(x => x.Value == bytecode[i]).Key}");
i++;
}
return mnemonic;
}
public static int GetIndex(string bytecode)
{
string[] arr = bytecode.Split(" ");
int length = arr.Length;
int inc = 0;
for (int i = 0; i < length; i++)
{
if (Instruction.vInstruction.TryGetValue(arr[i].ToString(), out int _)) inc++;
else if (int.TryParse(arr[i], out int _)) inc += 4;
else if (arr[i].StartsWith("</")) inc += 1;
}
return inc;
}
public static byte[] SerializeString(string str, int words)
{
byte[] strBytes = Encoding.UTF8.GetBytes(str);
int size = words * 4;
int difference = size - strBytes.Length;
List<byte> original = [.. strBytes[..(difference + 1)]];
byte[] toPad = [.. strBytes[(difference + 1)..]];
foreach (var item in strBytes) Console.WriteLine(item);
int padLength = toPad.Length;
int zeros = 4 - padLength;
for (int i = 0; i < zeros; i++)
{
original.Add(0);
}
for (int i = 0; i < padLength; i++)
{
original.Add(toPad[i]);
}
return [.. original];
}
public static string DeserializeString(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
}