如何在Python中表示字节数组(如Java中的byte [])?我需要使用gevent通过电线发送它。
byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00};
Answers:
在Python 3中,我们使用bytes对象,str在Python 2中也称为。
# Python 3
key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
# Python 2
key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
我发现使用该base64模块更方便...
# Python 3
key = base64.b16decode(b'130000000800')
# Python 2
key = base64.b16decode('130000000800')
您还可以使用文字...
# Python 3
key = b'\x13\0\0\0\x08\0'
# Python 2
key = '\x13\0\0\0\x08\0'
只需使用bytearray(Python 2.6和更高版本)代表可变的字节序列即可
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')
索引获取并设置单个字节
>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')
并且如果您需要它str(或bytes在Python 3中),它就像
>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'
fubar = str(key); print(len(key), len(fubar))产生6 38。在任何情况下(1)“字符串”都是非常模糊的术语(2)如果他想要可变性,则可以更改其原始列表
str不同工作的要点bytearray-已修复。我提到可变性主要是为了将其与区别开来bytes,但重点还在于,您根本不需要中间步骤来存储数据list。
struct.pack("<IH", 19, 8)……
Dietrich的答案可能仅仅是您需要描述的内容,即发送字节,但是例如,与您提供的代码更类似的将使用该bytearray类型。
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>>
bytearray如果需要字节数组,内置的方法确实是可行的。
bytearray('b', ...)不起作用。或者您可以删除它。
base64.b16decode(x)您可以简单地使用代替x.decode("hex")。它至少可以减少一分导入。:)