bytearray類型是python中的二進制數組類型,返回一個字節數組。
byte=bytearray(str,encoding,error)
str:待轉化的字符串,若該值為字符串,則encoding參數必須存在(為utf-8,gbk,Latin-1等編碼格式);若為b'xxx',則encoding參數不需要
特點:
1.該類型可以通過for..in...進行遍歷,遍歷的結果是0~255之間的值(表示字符編碼的二進制值或字母數字的ASCII值)
2.由於是數組,可以通過取值符號[]取值或更改。
3.主要用於對str進行計算
以下例子是對id進行加密計算
import hashlib
import base64
def encrypted_id(id):
magic = bytearray('3go8&$8*3*3h0k(2)2', 'utf-8')#轉化成bytearray字節數組
song_id = bytearray(id, 'utf-8')
magic_len = len(magic)
for i, sid in enumerate(song_id):
song_id[i] = sid ^ magic[i % magic_len]#對元素進行異或計算,返回值賦值給song_id
m = hashlib.md5(song_id)
result = m.digest()#對新的song_id進行加密,並返回二進制格式
result = base64.b64encode(result)#進行base64編碼
result = result.replace(b'/', b'_')
result = result.replace(b'+', b'-')
return result.decode('utf-8')#替換並解碼
print(encrypted_id('abc'))
