-
Notifications
You must be signed in to change notification settings - Fork 1
/
Packer.ts
49 lines (45 loc) · 1.33 KB
/
Packer.ts
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
import Uint1Array from "uint1array";
export class Packer {
buf: ArrayBuffer;
bytes: Uint8Array;
bits: Uint1Array;
position: number = 0;
constructor(size: number) {
this.buf = new ArrayBuffer(size);
this.bytes = new Uint8Array(this.buf);
this.bits = new Uint1Array(this.buf);
}
writeInt32(value: number) {
const bits = value
.toString(2) // Convert number to equivalent bit string!
.padStart(32, "0") // pad it with necessary number of zeroes
.split("") // split it to get each bit
.map((bit) => parseInt(bit)) // turn it into a number, slow-ish?
.reverse() // reverse it for order!
.forEach((bit) => {
this.bits[this.position] = bit;
this.position++;
});
}
writeInt8(value: number) {
const bits = value
.toString(2) // Convert number to equivalent bit string!
.padStart(8, "0") // pad it with necessary number of zeroes
.split("") // split it to get each bit
.map((bit) => parseInt(bit)) // turn it into a number, slow-ish?
.reverse() // reverse it for order!
.forEach((bit) => {
this.bits[this.position] = bit;
this.position++;
});
}
addBits(bits: number[]) {
bits.forEach((bit) => {
this.bits[this.position] = bit;
this.position++;
});
}
pack() {
return this.bytes;
}
}