| 10 | |
| 11 | |
| 12 | def encode(src, str_map): |
| 13 | dst = [] |
| 14 | src_len = 0 |
| 15 | |
| 16 | if len(src) == 0: |
| 17 | return '' |
| 18 | |
| 19 | while len(src): |
| 20 | src_len = len(src) |
| 21 | next_byte = [0] * 8 |
| 22 | |
| 23 | if src_len > 4: |
| 24 | next_byte[7] = src[4] & 0x1f |
| 25 | next_byte[6] = src[4] >> 5 |
| 26 | |
| 27 | if src_len > 3: |
| 28 | next_byte[6] = next_byte[6] | (src[3] << 3) & 0x1f |
| 29 | next_byte[5] = (src[3] >> 2) & 0x1f |
| 30 | next_byte[4] = src[3] >> 7 |
| 31 | |
| 32 | if src_len > 2: |
| 33 | next_byte[4] = next_byte[4] | (src[2] << 1) & 0x1f |
| 34 | next_byte[3] = (src[2] >> 4) & 0x1f |
| 35 | |
| 36 | if src_len > 1: |
| 37 | next_byte[3] = next_byte[3] | (src[1] << 4) & 0x1f |
| 38 | next_byte[2] = (src[1] >> 1) & 0x1f |
| 39 | next_byte[1] = (src[1] >> 6) & 0x1f |
| 40 | |
| 41 | if src_len > 0: |
| 42 | next_byte[1] = next_byte[1] | (src[0] << 2) & 0x1f |
| 43 | next_byte[0] = src[0] >> 3 |
| 44 | |
| 45 | for nb in next_byte: |
| 46 | dst.append(str_map[nb]) |
| 47 | |
| 48 | src = src[5:] |
| 49 | |
| 50 | if src_len < 5: |
| 51 | dst[-1] = padInt |
| 52 | if src_len < 4: |
| 53 | dst[-2] = padInt |
| 54 | dst[-3] = padInt |
| 55 | if src_len < 3: |
| 56 | dst[-4] = padInt |
| 57 | if src_len < 2: |
| 58 | dst[-5] = padInt |
| 59 | dst[-6] = padInt |
| 60 | |
| 61 | return ''.join((chr(i) for i in dst)) |
| 62 | |
| 63 | |
| 64 | def decode(src, alphabet): |