-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathVariableLength.cs
More file actions
121 lines (87 loc) · 2.85 KB
/
VariableLength.cs
File metadata and controls
121 lines (87 loc) · 2.85 KB
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
using GotaSoundIO.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GotaSequenceLib {
/// <summary>
/// Variable length.
/// </summary>
public static class VariableLength {
/// <summary>
/// Read variable length.
/// </summary>
/// <param name="r">The reader.</param>
/// <param name="limit">Max size the variable length can be.</param>
/// <returns>Variable length value.</returns>
public static uint ReadVariableLength(FileReader r, int limit = -1) {
//Get the temporary value.
uint temp = (uint)r.ReadByte();
//Get value.
uint val = (uint)temp & 0x7F;
int bytesRead = 1;
//Run until MSB is not set.
while ((temp & 0x80) > 0 && (limit == -1 || bytesRead < limit)) {
//Shift value to the left 7 bits.
val <<= 7;
//Get new temp value.
temp = r.ReadByte();
bytesRead++;
//Add the value to the value.
val |= temp & 0x7F;
}
return val;
}
/// <summary>
/// Write write variable length.
/// </summary>
/// <param name="w">The writer.</param>
/// <param name="val">Value to write.</param>
public static void WriteVariableLength(FileWriter w, uint val) {
//Write the value.
List<byte> nums = new List<byte>();
while (val > 0) {
//Add number.
nums.Insert(0, (byte)(val & 0x7F));
val >>= 7;
}
//Add MSB.
for (int i = 0; i < nums.Count - 1; i++) {
//Set MSB.
nums[i] |= 0x80;
}
//Safety.
if (nums.Count < 1) {
nums.Add(0);
}
//Write the value.
w.Write(nums.ToArray());
}
/// <summary>
/// Get the size of a variable length parameter.
/// </summary>
/// <param name="val">Value.</param>
/// <returns>The size of the variable length in bytes.</returns>
public static int CalcVariableLengthSize(uint val) {
//Write the value.
List<byte> nums = new List<byte>();
while (val > 0) {
//Add number.
nums.Insert(0, (byte)(val & 0x7F));
val >>= 7;
}
//Add MSB.
for (int i = 0; i < nums.Count - 1; i++) {
//Set MSB.
nums[i] |= 0x80;
}
//Safety.
if (nums.Count < 1) {
nums.Add(0);
}
//Return the size.
return nums.Count;
}
}
}