-
Notifications
You must be signed in to change notification settings - Fork 0
/
pack7.py
45 lines (34 loc) · 957 Bytes
/
pack7.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
#!/usr/bin/env python
bits = [''.join(['01'[i&(1<<b)>0] for b in xrange(7,-1,-1)]) for i in xrange(256)]
def pack_7bit(data):
buffer = 0
bitcount = 0
out = ""
while True:
if bitcount < 7:
buffer <<= 8
buffer |= ord(data[0])
data = data[1:]
bitcount += 8
out += chr(buffer >> (bitcount - 7))
buffer &= (1 << (bitcount - 7)) - 1
bitcount -= 7
if len(data) == 0: break
out += chr(buffer << (7 - bitcount))
return out
def unpack_7bit(data):
buffer = 0
bitcount = 0
out = ""
while True:
if bitcount < 8:
buffer <<= 7
buffer |= ord(data[0])
data = data[1:]
bitcount += 7
if bitcount >= 8:
out += chr(buffer >> (bitcount - 8))
buffer &= (1 << (bitcount - 8)) - 1
bitcount -= 8
if len(data) == 0: break
return out