Python中的字节数组 [英] Byte Array in Python

查看:127
本文介绍了Python中的字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中表示字节数组(如Java中的byte [])?我需要使用gevent通过电线发送它。

How can I represent a byte array (like in Java with byte[]) in Python? I'll need to send it over the wire with gevent.

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


推荐答案

在Python 3中,我们使用 bytes 对象,在Python 2中也称为 str

In Python 3, we use the bytes object, also known as str in Python 2.

# 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 模块更方便...

I find it more convenient to use the base64 module...

# Python 3
key = base64.b16decode(b'130000000800')

# Python 2
key = base64.b16decode('130000000800')

您也可以使用文字...

You can also use literals...

# Python 3
key = b'\x13\0\0\0\x08\0'

# Python 2
key = '\x13\0\0\0\x08\0'

这篇关于Python中的字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆