def encode(bindata): ''' Encode a bytearray to a Base91 string ''' l = len(bindata) b = 0 n = 0 out = '' for byte in bindata: b |= struct.unpack('B', byte)[0] << n n += 8 if n>13: v = b & 8191 if v > 88: b >>= 13 n -= 13 else: v = b & 16383 b >>= 14 n -= 14 out += base91_alphabet[v % 91] + base91_alphabet[v / 91] if n: out += base91_alphabet[b % 91] if n>7 or b>90: out += base91_alphabet[b / 91] return out