samedi 28 février 2015

Ascii string of bytes packed into bitmap/bitstring back to string?

I have a string that is packed such that each character was originally an unsigned byte but is stored as 7 bits and then packed into an unsigned byte array. I'm trying to find a quick way to unpack this string in Python but the function I wrote that uses the bitstring module works well but is very slow. It seems like something like this should not be so slow but I'm probably doing it very inefficiently...


This seems like something that is probably trivial but I just don't know what to use, maybe there is already a function that will unpack the string?



from bitstring import BitArray

def unpackString(raw):
msg = ''

bits = BitArray(bytes=raw)
mask = BitArray('0b01111111')

i = 0
while 1:
try:
iByte = (bits[i:i + 8] & mask).int
if iByte == 0:
msg += '\n'
elif iByte >= 32 and iByte <= 126:
msg += chr(iByte)
i += 7
except:
break

return msg

Aucun commentaire:

Enregistrer un commentaire