Byte Array in Python

d0ctor picture d0ctor · Sep 11, 2011 · Viewed 201.8k times · Source

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};

Answer

Dietrich Epp picture Dietrich Epp · Sep 11, 2011

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])

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'