-
Notifications
You must be signed in to change notification settings - Fork 0
/
BitReader.cs
62 lines (55 loc) · 1.32 KB
/
BitReader.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
using System;
using System.IO;
namespace TuckBytesInCode
{
//TODO ended up not using BitReader, but it could be usefull.
// Need to put this somewhere else - maybe it's own project
public class BitReader
{
public BitReader(Stream s)
{
BaseStream = s;
}
Stream BaseStream;
byte Current;
int BitsLeft;
const int BitsInByte = 8; //this is a bit silly.. no magic numbers here!
public bool[] ReadBits(int length)
{
int counter = 0;
bool[] bits = null;
while(counter < length)
{
while(BitsLeft > 0) {
//delay instantiate bits so that reads past then end of the stream return null
if (bits == null) {
bits = new bool[length];
}
bits[counter] = (1 << (BitsLeft - 1) & Current) != 0;
counter++;
BitsLeft--;
if (counter >= length) { break; }
}
if (counter >= length) { break; }
int next = BaseStream.ReadByte();
if (next == -1) { break; } //end of stream reached
Current = (byte)next;
BitsLeft = BitsInByte;
}
return bits;
}
public int ReadBitsAsInt(int length)
{
return BitsToInt(ReadBits(length));
}
public static int BitsToInt(bool[] bits)
{
if (bits == null) { return -1; }
int final = 0;
for(int b=0; b<bits.Length; b++) {
final |= (bits[b] ? 1 : 0) << (bits.Length - b - 1);
}
return final;
}
}
}