我该如何在Python中表示字节数组(类似于Java中的byte[])?我需要使用gevent将其发送到网络上。
byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00};
在Python 3中,我们使用bytes
对象,它在Python 2中也被称为str
。
# 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
(或在Python 3中作为bytes
)使用,那么它非常简单,只需执行以下操作:
>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'
fubar = str(key); print(len(key), len(fubar))
会产生 6 38
的结果。总之,(1) "string" 是一个非常模糊的术语 (2) 如果他想要可变性,他可以改变他原本的 list。 - John Machinbytearray
与str
处理方式不同的观点非常好-已修正。我提到可变性主要是为了将其与bytes
区分开,但重点也在于您根本不需要将数据作为list
的中间步骤。 - Scott Griffithsstruct.pack("<IH", 19, 8)
这样的东西... - John Machin另外一种选择是易于记录输出的日志:
hexs = "13 00 00 00 08 00"
logging.debug(hexs)
key = bytearray.fromhex(hexs)
让您能够轻松进行替换,如下所示:
hexs = "13 00 00 00 08 {:02X}".format(someByte)
logging.debug(hexs)
key = bytearray.fromhex(hexs)
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>>
bytearray
确实是最好的选择。 - Scott Griffithsbytearray('b', ...)
无法使用。或者您可以直接删除它。 - John Machin
x.decode("hex")
代替base64.b16decode(x)
。这样至少可以少导入一个模块 :)。 - Dolda2000bytes.fromhex('130000000800')
的意思是将十六进制字符串转换为字节对象。 - Mark Tolonen