python将bytearray转换为列表中的数字

chr*_*ina 3 python bytearray

对于以下python代码:

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

如果我使用:

print state
Run Code Online (Sandbox Code Playgroud)

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

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

小智 6

您可以使用相同名称的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]        
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 5

索引bytearray结果以无符号字节为单位。

>>> pt[0]
50
>>> pt[5]
90
Run Code Online (Sandbox Code Playgroud)