Skip to content

Instantly share code, notes, and snippets.

@AntiKnot
Created March 4, 2022 04:01
Show Gist options
  • Save AntiKnot/d86d0e68a839923b9a7bd6515d35302d to your computer and use it in GitHub Desktop.
Save AntiKnot/d86d0e68a839923b9a7bd6515d35302d to your computer and use it in GitHub Desktop.
how base64 work
# make a base64 index
index = [
"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", "+", "/"
]
# function Unicode to UInt8Array
def Unicode2UInt8Array(string):
return [ord(c) for c in string]
# function UInt8Array to Binary
def UInt8Array2Binary(arr):
return ''.join(format(x, '08b') for x in arr)
# function every 6 length binary in stream to int
def Binary2Int(binary):
return int(binary, 2)
# function int to char in index
def Int2Char(int):
return index[int]
# function chunk string in fixed length
def chunk(string, length):
return [string[i:i + length] for i in range(0, len(string), length)]
def base64(string):
stream = UInt8Array2Binary(Unicode2UInt8Array(string))
chunks = chunk(stream, 6)
return ''.join(Int2Char(Binary2Int(chunk)) for chunk in chunks)
if __name__ == '__main__':
assert base64('foo') == 'Zm9v'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment