Byte Array in Python

Question:

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};
Asked By: d0ctor

||

Answers:

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'x13x08'

# Python 2
key = 'x13x08'
Answered By: Dietrich Epp

Dietrich’s answer is probably just the thing you need for what you describe, sending bytes, but a closer analogue to the code you’ve provided for example would be using the bytearray type.

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

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

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

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'x13xffx00x00x08x00')

and if you need it as a str (or bytes in Python 3), it’s as simple as

>>> bytes(key)
'x13xffx00x00x08x00'
Answered By: Scott Griffiths

An alternative that also has the added benefit of easily logging its output:

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

allows you to do easy substitutions like so:

hexs = "13 00 00 00 08 {:02X}".format(someByte)
logging.debug(hexs)
key = bytearray.fromhex(hexs)
Answered By: TomSchober
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.