簡體   English   中英

Python 將字符串數組轉換為字節數組

[英]Python convert array of strings to array of bytes

我正在嘗試將字符串數組oldlist = ['00000100', '10100001', '11000001', '11100001']轉換為二進制值的字節作為十六進制代碼,因此結果列表看起來像這樣newlist = [b'\x04', b'\xa1', b'\xc1', b'\xe1'] 我得到了遍歷第一個列表並附加到前一個列表或進行某種列表組合的基本概念。 但我找不到將“00000100”轉換為“b'\x04'”的 function

您可以使用int(number, 2)將字符串轉換為 integer:

oldlist = ["00000100", "10100001", "11000001", "11100001"]

out = list(map(lambda x: bytes([int(x, 2)]), oldlist))
print(out)

印刷:

[b'\x04', b'\xa1', b'\xc1', b'\xe1']

你可以做的是使用string.getBytes();

您首先需要將二進制字符串轉換為 integer。 為此,您可以使用基數為 2 的 int() 方法。然后要將其轉換為字節,請使用類似 bytes([x]) 的 bytes() 方法。

>>> oldlist = ['00000100', '10100001', '11000001', '11100001']
>>> list(map(lambda x: bytes([int(x, 2)]), oldlist))
[b'\x04', b'\xa1', b'\xc1', b'\xe1']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM