Mercurial > touhou
comparison pytouhou/utils/bitstream.py @ 0:6b2c7af2384c
Hello Gensokyo _o/
author | Thibaut Girka <thib@sitedethib.com> |
---|---|
date | Sun, 31 Jul 2011 21:32:12 +0200 |
parents | |
children | ab826bc29aa2 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:6b2c7af2384c |
---|---|
1 class BitStream(object): | |
2 def __init__(self, io): | |
3 self.io = io | |
4 self.bits = 0 | |
5 self.byte = 0 | |
6 | |
7 | |
8 def seek(self, offset, whence=0): | |
9 self.io.seek(offset, whence) | |
10 self.byte = 0 | |
11 self.bits = 0 | |
12 | |
13 | |
14 def tell(self): | |
15 return self.io.tell() | |
16 | |
17 | |
18 def tell2(self): | |
19 return self.io.tell(), self.bits | |
20 | |
21 | |
22 def read_bit(self): | |
23 if not self.bits: | |
24 self.byte = ord(self.io.read(1)) | |
25 self.bits = 8 | |
26 self.bits -= 1 | |
27 return (self.byte >> self.bits) & 0x01 | |
28 | |
29 | |
30 def read(self, nb_bits): | |
31 value = 0 | |
32 for i in range(nb_bits - 1, -1, -1): | |
33 value |= self.read_bit() << i | |
34 return value | |
35 | |
36 | |
37 def write_bit(self, bit): | |
38 if self.bits == 8: | |
39 self.io.write(chr(self.byte)) | |
40 self.bits = 0 | |
41 self.byte = 0 | |
42 self.byte &= ~(1 << (7 - self.bits)) | |
43 self.byte |= bit << (7 - self.bits) | |
44 self.bits += 1 | |
45 | |
46 | |
47 def write(self, bits, nb_bits): | |
48 for i in range(nb_bits): | |
49 self.write_bit(bits >> (nb_bits - 1 - i) & 0x01) | |
50 | |
51 | |
52 def flush(self): | |
53 self.io.write(chr(self.byte)) | |
54 self.bits = 0 | |
55 self.byte = 0 | |
56 self.io.flush() | |
57 |