-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitOutputStream.cpp
More file actions
94 lines (74 loc) · 1.56 KB
/
Copy pathBitOutputStream.cpp
File metadata and controls
94 lines (74 loc) · 1.56 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
#ifndef BITOUTPUTSTREAM_H_
#define BITOUTPUTSTREAM_H_
/*
* BitOutputStream.cpp
* Author: saito
* Date: May 18, 2018
* About:
*/
#include <fstream>
#include <iostream>
using namespace std;
class BitOutputStream {
private:
unsigned char buffer=0;
char current=7;
ofstream* output;
public:
//insert the next bit into the buffer. Flush write if full
void put(bool bit){
/* if(!bit) {
cout << "0";
} else {
cout << "1";
}*/
if(current <= -1){
flush();
}
buffer |= (bit << current);
current--;
};
/*Prorate unnecessary bytes, and put them bit-by-bit*/
void write(unsigned int value){
char size = 1;
if(value >= 1 << 8)
size++;
if(value >= 1 << 16)
size++;
if (value >= 1 << 24)
size++;
for (int index = (size * 8) - 1; index >= 0;index--){
//Shift each bit such that it is in the 1 position to AND it.
put((value >> index) & 1);
}
};
//MANUAL SIZING VERSION
void write(unsigned int value, char size){
for (int index = size - 1; index >= 0;index--){
//Shift each bit such that it is in the 1 position to AND it.
bool bit = (value >> index) & 1;
put(bit);
}
};
//Get a new set of bits and reset the buffer
void flush(){
output->put(buffer);
buffer = 0;
current = 7;
};
void connect(ofstream& stream){
output = &stream;
};
//Wrapper to relay close() command. FLUSH THE BUFFER.
void close(){
if(current >= -1){
flush();
}
output->close();
};
//Wrapper to relay close() command. DO NOT Flush the buffer.
void ForceClose(){
output->close();
};
};
#endif /* BITOUTPUTSTREAM_H_ */