forked from gzc/CLRS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryStdOut.cpp
75 lines (63 loc) · 1.56 KB
/
BinaryStdOut.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
/*************************************************************************
> File Name: BinaryStdOut.cpp
> Author:
> Mail:
> Created Time: Wed 14 Jan 2015 09:18:56 PM CST
************************************************************************/
#include "BinaryStdOut.h"
#include<iostream>
using namespace std;
BinaryStdOut::BinaryStdOut(string filename) {
open(filename);
}
bool BinaryStdOut::open(string filename) {
fout.open(filename.c_str(), ios::out|ios::binary);
if (!fout.is_open()) {
cout << "Error opening file" << endl;
exit (1);
}
}
void BinaryStdOut::clearBuffer() {
if(N == 0) return;
if (N > 0) buffer <<= (8 - N);
fout << buffer;
N = 0;
buffer = 0;
}
void BinaryStdOut::writeBit(bool bit) {
buffer <<= 1;
if (bit) buffer |= 1;
N++;
if (N == 8) clearBuffer();
}
void BinaryStdOut::writeChar(char ch) {
if (N == 0) {
fout << ch;
return;
}
for (int i = 0; i < 8; i++) {
bool bit = ((ch >> (8 - i - 1)) & 1 ) == 1;
writeBit(bit);
}
}
void BinaryStdOut::write(bool x) {
writeBit(x);
}
void BinaryStdOut::write(char x) {
writeChar(x);
}
void BinaryStdOut::write(int x) {
writeChar((x >> 24) & 0xff);
writeChar((x >> 16) & 0xff);
writeChar((x >> 8) & 0xff);
writeChar((x >> 0) & 0xff);
}
void BinaryStdOut::flush() {
clearBuffer();
fout.flush();
}
void BinaryStdOut::close() {
flush();
fout.close();
cout << "-------------------- BinaryStdOut Writing Closing --------------------" << endl;
}