chiark / gitweb /
added example
[secnet.git] / base91.py
1 import struct
2
3 base91_alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
4         'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
5         'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
6         'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
7         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '#', '$',
8         '%', '&', '(', ')', '*', '+', ',', '.', '/', ':', ';', '<', '=',
9         '>', '?', '@', '[', ']', '^', '_', '`', '{', '|', '}', '~', '"']
10
11 decode_table = dict((v,k) for k,v in enumerate(base91_alphabet))
12
13 def decode(encoded_str):
14     v = -1
15     b = 0
16     n = 0
17     out = bytearray()
18     for strletter in encoded_str:
19         if not strletter in dectable:
20             continue
21         c = dectable[strletter]
22         if(v < 0):
23             v = c
24         else:
25             v += c*91
26             b |= v << n
27             n += 13 if (v & 8191)>88 else 14
28             while True:
29                 out += struct.pack('B', b&255)
30                 b >>= 8
31                 n -= 8
32                 if not n>7:
33                     break
34             v = -1
35     if v+1:
36         out += struct.pack('B', (b | v << n) & 255 )
37     return out
38