题
如何在 Python 中表示字节数组(如 Java 中的 byte[])?我需要用 gevent 通过网络发送它。
byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00};
解决方案
在Python 3中,我们使用bytes
对象,在Python 2中也称为str
。
通用标签
我发现使用base64
模块更方便...
通用标签
您也可以使用文字... 通用标签
其他提示
只是使用一个 bytearray
(Python2.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
在Python3)中,就这么简单
>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'
另一种方法也具有轻松记录其输出的额外好处: 通用标签
允许您像这样进行简单替换: 通用标签
迪特里希的答案可能正是您所描述的内容所需要的,发送字节,但是与您提供的代码更接近的类似物是使用 bytearray
类型。
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>>
不隶属于 StackOverflow