python 将字节数组转换为列表中的数字

python convert bytearray to numbers in list

对于以下 python 代码:

pt  = bytearray.fromhex('32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34')
state = bytearray(pt)

如果我使用:

print state

给出2Cö¨ˆZ0?11˜¢à74

那么如何恢复bytearray中的内容呢?例如,将它们放在 [].

这样的列表中

索引 bytearray 会产生无符号字节。

>>> pt[0]
50
>>> pt[5]
90

您可以使用简单的字符串方法创建自己的方法:

string = '32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34'
number = [int(i, 16) for i in string.split()]

现在你有一个你想要的转换数字列表。

您可以使用 python 在字节数组和列表之间进行转换 内置同名函数。

>>> x=[0,1,2,3,4]      # create a list 
>>> print x
[0, 1, 2, 3, 4]
>>> y = bytearray(x)   # convert the list to a bytearray    
>>> print y
(garbled binary)               <-- prints UGLY!
>>> z = list(y)        # convert the bytearray back into a list
>>> print z
[0, 1, 2, 3, 4]        

我一直在寻找 'How may you convert binary into decimal values?' 的答案并找到了这个问题,所以我想尽可能多地完成 Malik Brahimi's 答案。

基本上,您可以做的是创建一个列表,然后遍历它们以创建十进制列表:

b_list = ['0', '1', '10', '11', '100', '101'] # Note, that values of list are strings
res = [int(n, 2) for n in b_list] # Convert from base two to base ten
print(res)

# Output:
# User@DESKTOP-CVQ282P MINGW64 ~/desktop
# $ python backpool.py
# [0, 1, 2, 3, 4, 5]

您可能会注意到,我们可以使用这种方式来转换具有不同基数的值:二进制、十六进制等。