Python中的字节数组
我该如何在Python中表示一个字节数组(就像Java中的byte[])呢?我需要用gevent把它发送出去。
byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00};
4 个回答
6
还有一种替代方案,它的好处是可以很方便地记录输出内容:
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)
36
只需使用一个 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'
95
在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'