Python中的Byte数组

如何在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' 

另一种方法也可以轻松logging其输出:

 hexs = "13 00 00 00 08 00" logging.debug(hexs) key = bytearray.fromhex(hexs) 

允许你做这样简单的replace:

 hexs = "13 00 00 00 08 {:02X}".format(someByte) logging.debug(hexs) key = bytearray.fromhex(hexs) 

Dietrich的答案可能就是你所描述的东西,发送字节,但是与你提供的代码更接近的模拟将使用bytearraytypes。

 >>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00]) >>> bytes(key) b'\x13\x00\x00\x00\x08\x00' >>>