Created
December 3, 2015 10:52
-
-
Save mfukar/e23fd428a2da6ab43ed2 to your computer and use it in GitHub Desktop.
A buffer of bits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import struct | |
class bitbuffer: | |
# TODO: need reader? | |
def __init__(self): | |
self.buffer = b'' | |
self.byte = 0 | |
self.bit_pos = 7 | |
def append(self, value, nbits): | |
mask = 1 << (nbits - 1) | |
while (mask): | |
if value & mask: | |
self.byte |= (1 << self.bit_pos) | |
self.bit_pos -= 1 | |
mask >>= 1 | |
if self.bit_pos < 0: | |
self.buffer += struct.pack('<B', self.byte) | |
self.bit_pos = 7 | |
self.byte = 0 | |
def flush(self): | |
if self.bit_pos != 7: | |
self.buffer += struct.pack('<B', self.byte) | |
def get_buffer(self): | |
return self.buffer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment