Created
October 25, 2024 10:43
-
-
Save mydreambei-ai/8e459579ee77b30462a96b6fde0af943 to your computer and use it in GitHub Desktop.
base64 encode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def base64_unit(input_bytes): | |
base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
padding = {1: 2, 2: 1, 0: 0}[len(input_bytes) % 3] | |
while len(input_bytes) < 3: | |
input_bytes += b'\x00' | |
num = int.from_bytes(input_bytes, byteorder='big') | |
o = [] | |
count = 0 | |
for j in range(18, -1, -6): | |
if count + padding >= 4: | |
o.append("=") | |
count += 1 | |
continue | |
index = num >> j & 0x3F | |
o.append(base64_chars[index]) | |
count += 1 | |
return "".join(o) | |
def base64_encode(input_bytes): | |
o = [] | |
for i in range(0, len(input_bytes), 3): | |
unit = input_bytes[i: i+3] | |
o.append(base64_unit(unit)) | |
return "".join(o) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment