forked from gzc/CLRS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryStdIn.cpp
84 lines (68 loc) · 1.56 KB
/
BinaryStdIn.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
/*************************************************************************
> File Name: BinaryStdIn.cpp
> Author:
> Mail:
> Created Time: Wed 14 Jan 2015 08:14:15 PM CST
************************************************************************/
#include "BinaryStdIn.h"
BinaryStdIn::BinaryStdIn(string filename) {
open(filename);
}
bool BinaryStdIn::open(string filename)
{
fin.open(filename.c_str(), std::ios::binary);
if (!fin.is_open()) {
cout << "Error opening file" << endl;
exit (1);
}
fillBuffer();
return true;
}
bool BinaryStdIn::fillBuffer() {
char ch;
fin >> ch;
buffer = ch;
N = 8;
}
bool BinaryStdIn::readBool() {
N--;
bool bit = ((buffer >> N) & 1) == 1;
if (N == 0) fillBuffer();
#ifdef DEBUG
cout << "Function readBool() return : " << bit << endl;
#endif
return bit;
}
char BinaryStdIn::readChar() {
if(N == 8) {
char x = buffer;
fillBuffer();
return x;
}
char x = buffer;
x <<= (8-N);
int oldN = N;
fillBuffer();
N = oldN;
unsigned char tmp = (unsigned char)buffer;
x |= ( tmp >> N);
#ifdef DEBUG
cout << "Function readChar() return : " << x << endl;
#endif
return x;
}
int BinaryStdIn::readInt() {
int x = 0;
for (int i = 0; i < 4; i++) {
char c = readChar();
x <<= 8;
x |= c;
}
#ifdef DEBUG
cout << "Function readInt() return : " << x << endl;
#endif
return x;
}
void BinaryStdIn::close() {
fin.close();
}