85

如何在 Python 中表示一个字节数组(比如在 Java 中使用 byte[])?我需要用 gevent 通过网络发送它。

byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00};
4

4 回答 4

88

在 Python 3 中,我们使用对象,在 Python 2 中bytes也称为对象。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'
于 2011-09-11T18:50:03.100 回答
35

只需使用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'
于 2011-09-11T19:06:55.797 回答
5

另一种方法还具有轻松记录其输出的额外好处:

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)
于 2015-07-11T16:27:12.337 回答
3

迪特里希的答案可能正是您所描述的内容所需要的东西,发送字节,但与您提供的代码更接近的类似物是使用bytearray类型。

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>> 
于 2011-09-11T18:58:18.423 回答