def Enbs64(s):
# 编码后的结果
result = ''
# 二进制数据
bin_data = ''
# Base64编码对照表
bs64_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', '+', '/']
# 转为 ASCII 再转为 二进制
for i in s:
# 8位组成的单个字节
bytes_8 = bin(ord(i))[2:]
if len(bytes_8) < 8:
# 不够8位,在前面用0填充
bytes_8 = '0' * (8 - len(bytes_8)) + bytes_8
bin_data += bytes_8
# 在二进制数据里,每次取出6个转为整数,作为下标从bs64编码表里取值
for i in range(0, len(bin_data), 6):
# 6位组成的单个字节
bytes_6 = bin_data[i:i + 6]
# 不足6位,在后面用0填充
if len(bytes_6) < 6:
bytes_6 = bytes_6 + '0' * (6 - len(bytes_6))
index = int(bytes_6, 2)
result += bs64_table[index]
# 全部编码后,不足4字节的用 "=" 填充
if len(result) % 4 != 0:
result = result + '=' * (4 - len(result) % 4)
return result
print(Enbs64('Welcome'))