Skip to content

Instantly share code, notes, and snippets.

@alex-berezan
Created May 24, 2018 05:27
Show Gist options
  • Save alex-berezan/4cc74a12636dc7edbd67c5b191d8235a to your computer and use it in GitHub Desktop.
Save alex-berezan/4cc74a12636dc7edbd67c5b191d8235a to your computer and use it in GitHub Desktop.
def convert_base64(bytes):
def not_null(x):
return 0 if x is None else x
i = 0
result = []
while i < len(bytes):
PADDING_INDEX = 64
base64_table = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '=']
a = bytes[i]
b = bytes[i+1] if len(bytes) > i+1 else None
c = bytes[i+2] if len(bytes) > i+2 else None
x1 = a >> 2
x2 = ((a & 0b11) << 4) | (not_null(b) >> 4)
if b is None:
x3 = PADDING_INDEX
else:
x3 = ((b & 0b00001111) << 2) | (not_null(c) >> 6)
if c is None:
x4 = PADDING_INDEX
else:
x4 = (c & 0b00111111)
result.append(base64_table[x1])
result.append(base64_table[x2])
result.append(base64_table[x3])
result.append(base64_table[x4])
i += 3
return "".join(result)
# test
def run_test(s):
bytes = [ord(c) for c in s]
result = convert_base64(bytes)
print("{} -> {}".format(s, str(result)))
run_test('M')
run_test('Ma')
run_test('Man')
run_test('any carnal pleas')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment