...
 
Commits (2)
class Base64Converter:
def __init__(self):
self.d = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
def encode(self, f):
s = ''
data = f.read(3)
......@@ -13,9 +13,8 @@ class Base64Converter:
return s
def decode(self, f):
ds = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
digits = {}
for pos, digit in enumerate(ds):
for pos, digit in enumerate(self.d):
digits[digit] = pos
bs = bytes()
......@@ -56,11 +55,9 @@ class Base64Converter:
return f'{d[index1]}{d[index2]}{d[index3]}{d[index4]}'
def decode4chars(self, s, d):
ds = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
if not isinstance(s, str) or len(s) != 4 or \
not all([ch in ds for ch in s[:2]]) or \
not all([ch in ds + '=' for ch in s[2:]]):
not all([ch in self.d for ch in s[:2]]) or \
not all([ch in self.d + '=' for ch in s[2:]]):
raise ValueError(f'{s} is not a base64 encoded string')
int1 = d[s[0]]
......
......@@ -60,7 +60,7 @@ which in Hex is 49338F, and we have our test.
The inverse adds another twist, which is that when a byte can be represented
by a printable ASCII character, that is how Python represents it by default:
>>> b64.decode4chars('STOP', '')
>>> b64.decode4chars('STOP', {'S':18, 'T':19, 'O':14, 'P':15})
b'I3\x8f'
A very helpful resource for working with binary data in Python is:
......