编码部分,base64_encode.py
def b64encode(word):
base64_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
bin_word_list = ''
for each in word:
temp = bin(ord(each))[2:].zfill(8)
bin_word_list += temp
mod = len(bin_word_list) % 6
if mod != 0:
bin_word_list += (6-mod)*'0'
assert len(bin_word_list) % 6 == 0
base64_encode = ''
for each1 in range(0, len(bin_word_list), 6):
temp = bin_word_list[each1:each1+6]
temp = int(temp, 2)
base64_encode += base64_map[temp]
if mod != 0:
base64_encode += (6-mod)//2*'='
return base64_encode
解码部分,base64_decode.py
def b64decode(word):
base64_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
bin_word_list = ''
for each in word.split('=')[0]:
temp = bin(base64_map.index(each))[2:].zfill(6)
bin_word_list += temp
bin_word_list= bin_word_list[:-(word.count('=')*2)]
base64_decode = ''
for each1 in range(0, len(bin_word_list), 8):
temp = bin_word_list[each1:each1+8]
temp = int(temp, 2)
base64_decode += chr(temp)
return(base64_decode)
测试部分,90轮
import base64_decode
import base64_encode
import random
for each in range(90):
a=random.sample('qwerthucjijciosjoad',8)
origin_word=''.join(_ for _ in a)
after_encode=base64_encode.b64encode(origin_word)
after_decode=base64_decode.b64decode(after_encode)
assert after_decode==origin_word
print('pass')