-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitStreamer.cpp
88 lines (77 loc) · 1.4 KB
/
BitStreamer.cpp
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
#include "BitStreamer.h"
// gets string of 0 and 1 and converts to 8 bits decimal
char binToDec(string& bits)
{
unsigned int num = 0;
unsigned int n;
int j = 7;
for (int i = 0; i < bits.length(); i++)
{
n = bits[i];
n -= 48;
num += n * (pow(2, j));
j--;
}
return num;
}
BitStreamer::BitStreamer()
{
bits = new string();
}
BitStreamer::~BitStreamer()
{
delete bits;
}
int BitStreamer::totalSize()
{
return bits->length() + 8;
}
void BitStreamer::flush()
{
stream = "";
tmp = "";
*bits = "";
}
void BitStreamer::extractStream(const string& newStr)
{
int sub = 8 - stream.length();
tmp += stream;
for (int i = 0; i < sub; i++)
tmp += newStr[i];
stream = "";
for (int i = sub; i < newStr.length(); i++)
stream += newStr[i];
(*bits) += binToDec(tmp);
tmp = "";
}
void BitStreamer::operator <<(const string& str)
{
if (str.length() + stream.length() >= 8)
extractStream(str);
else
stream += str;
}
string* BitStreamer::getBits()
{
return bits;
}
string BitStreamer::finish(bool addCompletion, bool addDiff)
{
int len = stream.length();
int i = 0;
// complete to byte
if (addCompletion)
{
if (len > 0 && len < 8)
{
for (i = 0; i < (8 - (len % 8)); i++)
stream += "0";
(*bits) += binToDec(stream);
}
}
stream = "";
if (addDiff)
return (char)i + (*bits);
else
return (*bits);
}