-
Notifications
You must be signed in to change notification settings - Fork 5
/
bitio.py
91 lines (74 loc) · 2.16 KB
/
bitio.py
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
"""
比特流的读写
"""
class BitWriter(object):
def __init__(self, f):
self.accumulator = 0
self.bcount = 0
self.out = f
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.flush()
def __del__(self):
try:
self.flush()
except ValueError: # I/O operation on closed file.
pass
def write_bit(self, bit):
if self.bcount == 8:
self.flush()
if bit:
self.accumulator |= 1 << 7 - self.bcount
self.bcount += 1
def write_bits(self, bits, n):
while n > 0:
self.write_bit(bits & 1 << n - 1)
n -= 1
def flush(self):
self.out.write(bytearray([self.accumulator]))
self.accumulator = 0
self.bcount = 0
class BitReader(object):
def __init__(self, f):
self.input = f
self.accumulator = 0
self.bcount = 0
self.read = 0
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def read_bit(self):
if not self.bcount:
a = self.input.read(1)
if a:
self.accumulator = ord(a)
self.bcount = 8
self.read = len(a)
rv = (self.accumulator & (1 << self.bcount - 1)) >> self.bcount - 1
self.bcount -= 1
return rv
def read_bits(self, n):
v = 0
while n > 0:
v = (v << 1) | self.read_bit()
n -= 1
return v
if __name__ == '__main__':
with open('temp_files/bitio_test.dat', 'wb') as outfile:
with BitWriter(outfile) as writer:
chars = '12345abcde'
for ch in chars:
writer.write_bits(ord(ch), 7)
cnt = 98
writer.write_bits(cnt, 7)
with open('temp_files/bitio_test.dat', 'rb') as infile:
with BitReader(infile) as reader:
chars = []
while True:
x = reader.read_bits(7)
if not reader.read: # End-of-file?
break
chars.append(chr(x))
print(''.join(chars))