Mercurial > touhou
diff 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 |
line wrap: on
line diff
new file mode 100644 --- /dev/null +++ b/pytouhou/utils/bitstream.py @@ -0,0 +1,57 @@ +class BitStream(object): + def __init__(self, io): + self.io = io + self.bits = 0 + self.byte = 0 + + + def seek(self, offset, whence=0): + self.io.seek(offset, whence) + self.byte = 0 + self.bits = 0 + + + def tell(self): + return self.io.tell() + + + def tell2(self): + return self.io.tell(), self.bits + + + def read_bit(self): + if not self.bits: + self.byte = ord(self.io.read(1)) + self.bits = 8 + self.bits -= 1 + return (self.byte >> self.bits) & 0x01 + + + def read(self, nb_bits): + value = 0 + for i in range(nb_bits - 1, -1, -1): + value |= self.read_bit() << i + return value + + + def write_bit(self, bit): + if self.bits == 8: + self.io.write(chr(self.byte)) + self.bits = 0 + self.byte = 0 + self.byte &= ~(1 << (7 - self.bits)) + self.byte |= bit << (7 - self.bits) + self.bits += 1 + + + def write(self, bits, nb_bits): + for i in range(nb_bits): + self.write_bit(bits >> (nb_bits - 1 - i) & 0x01) + + + def flush(self): + self.io.write(chr(self.byte)) + self.bits = 0 + self.byte = 0 + self.io.flush() +