原理
轉碼過程例子:
3*8=4*6 內存1個字節占8位 轉前: s 1 3 先轉成ascii:對應 115 49 51 2進制: 01110011 00110001 00110011 6個一組(4組) 011100110011000100110011 然后才有后面的 011100 110011 000100 110011 然后計算機一個字節占8位,不夠就自動補兩個高位0了 所以有了高位補0 科學計算器輸入 00011100 00110011 00000100 00110011 得到 28 51 4 51 查對下照表 c z E z
python實現:
import 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("s13"))
應用
加密解密字符串:
字符串必須先要組成bytes string
import base64 def solve(str): #轉成bytes string bytesString = str.encode(encoding="utf-8") print(bytesString) #base64 編碼 encodestr = base64.b64encode(bytesString) print(encodestr) print(encodestr.decode()) #解碼 decodestr = base64.b64decode(encodestr) print(decodestr.decode()) if __name__ == '__main__': solve("ABC")
加密解密圖片:
import base64 with open("nfsq.jpg","rb") as f: # b64encode是編碼,b64decode是解碼 base64_data = str(base64.b64encode(f.read()), encoding='utf-8') # base64.b64decode(base64data) print(base64_data)
html顯示:
<img src="data:image/jpg;base64,這里是base64的編碼"/>
打算寫image2base64的程序,以交互式方式運行正確,寫成腳本卻報錯“AttributeError: module 'base64' has no attribute 'b64decode'”。
解決方法:我的程序名"base64.py"與包名沖突了,因此改名即可。
參考鏈接:
1. https://blog.csdn.net/XiangLanLee/article/details/84136519
2. https://www.cnblogs.com/lanzhi/p/6468386.html
3. https://baike.baidu.com/item/base64/8545775?fr=aladdin