天天看點

python3 數組轉字元串_Python3.x将bytearray的字元串表示形式轉換回字元串

如注釋中所述,使用base64以文本形式發送二進制資料。在import base64

def xor_strings(xs, ys):

return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys)).encode()

# ciphertext is bytes

ciphertext = xor_strings("foo", "bar")

# >>> b'\x04\x0e\x1d'

# ciphertext_b64 is *still* bytes, but only "safe" ones (in the printable ASCII range)

ciphertext_b64 = base64.encodebytes(ciphertext)

# >>> b'BA4d\n'

現在我們可以傳輸位元組:

^{pr2}$

收件人可以通過以下方式檢索原始郵件:# ...reading bytes from a file (or a network socket)

with open('/tmp/output', 'rb') as f:

ciphertext_b64_2 = f.read()

# ...or by reading bytes from a string

ciphertext_b64_2 = safe_string.encode('ascii')

# >>> b'BA4d\n'

# and finally decoding them into the original nessage

ciphertext_2 = base64.decodestring(ciphertext_b64_2)

# >>> b'\x04\x0e\x1d'

當然,在将位元組寫入檔案或網絡時,首先将其編碼為base64是多餘的。如果密文是唯一的檔案内容,則可以直接寫入/讀取。隻有當密文是更高結構(JSON、XML、配置檔案…)的一部分時,才有必要再次将其編碼為base64。在

關于“解碼”和“編碼”兩個詞用法的注釋。在對字元串進行編碼意味着将它從抽象意義(“字元清單”)轉換為可存儲的表示(“位元組清單”)。此操作的确切結果取決于所使用的位元組編碼。例如:ASCII編碼将一個字元映射到一個位元組(作為權衡,它不能映射Python字元串中可能存在的所有字元)。在

UTF-8編碼将一個字元映射為1-5個位元組,具體取決于字元。在

解碼一個位元組數組意味着将它從“位元組清單”重新轉換回“字元清單”。當然,這需要事先知道位元組編碼最初是什麼。

上面的ciphertext_b64是一個位元組清單,在Python控制台上用b'BA4d\n'表示。在

由于base64是ASCII的一個子集,當列印到控制台時,它的等價字元串safe_string看起來非常相似'BA4d\n'。在

然而,資料類型仍然有根本的不同。不要讓控制台輸出欺騙你。在