用python实现base64算法

# 使用标准库里的base64
import base64

content = 'Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.'
print(content.encode())
a = base64.b64encode(content.encode())
print(a)
b = base64.b64decode(a).decode()
print(b)

# b = base64.b64decode('SSBMb3ZlIFlvdQ==').decode()
# print(b)
#
# b = base64.b64decode('U28gZG8gSQ==').decode()
# print(b)

# 实现base64方法
# def base(string: str) -> str:
#     oldstr = ''
#     newstr = []
#     base = ''
#     base64_list = ['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', '+', '/']
#     # 把原始字符串转换为二进制,用bin转换后是0b开头的,所以把b替换了,首位补0补齐8位
#     for i in string:
#         oldstr += '{:08}'.format(int(str(bin(ord(i))).replace('0b', '')))
#     # 把转换好的二进制按照6位一组分好,最后一组不足6位的后面补0
#     for j in range(0, len(oldstr), 6):
#         newstr.append('{:<06}'.format(oldstr[j:j + 6]))
#     # 在base_list中找到对应的字符,拼接
#     for l in range(len(newstr)):
#         base += base64_list[int(newstr[l], 2)]
#     # 判断base字符结尾补几个‘=’
#     if len(string) % 3 == 1:
#         base += '=='
#     elif len(string) % 3 == 2:
#         base += '='
#     return base
#
#
# print(base("I Love You"))

猜你喜欢

转载自blog.csdn.net/liu201812/article/details/113684922