-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitWriter.cpp
More file actions
55 lines (44 loc) · 1.21 KB
/
BitWriter.cpp
File metadata and controls
55 lines (44 loc) · 1.21 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
#include "BitWriter.h"
using namespace std;
BitWriter::BitWriter(string filename) {
out = new ofstream(filename, ofstream::app);
}
BitWriter::~BitWriter() {
out->close();
delete out;
}
int BitWriter::write_bits(int num_bits, unsigned long long int data) {
// writes to buffer and left justifies
if (num_bits + counter > 64) { // error
cout << "will overwrite content of buffer" << endl;
abort();
}
// add data to buffer after shifting over
buffer |= (((unsigned long long int) data ) << (64-counter-num_bits));
counter += num_bits;
// actual writing performed internally
this->_write();
return num_bits;
}
void BitWriter::flush() {
// write final byte
this->_final_write();
}
void BitWriter::_write() { // write bits until count < 8
while (counter >= 8) {
char byte = (char) (buffer >> 56);
out->put(byte);
buffer <<= 8;
counter -= 8;
}
}
void BitWriter::_final_write() { // write final byte if counter != 0
if (counter == 0) return;
char byte = (char) (buffer >> 56);
out->put(byte);
out->flush();
}
void BitWriter::_print_state() {
bitset<64> bs(buffer);
cout << "buffer: " << bs << endl;
}