Byte Array in Python Byte Array in Python python python

Byte Array in Python


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

# Python 3key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])# Python 2key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])

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

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

You can also use literals...

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


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

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

Indexing get and sets the individual bytes

>>> key[0]19>>> key[1]=0xff>>> keybytearray(b'\x13\xff\x00\x00\x08\x00')

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

>>> bytes(key)'\x13\xff\x00\x00\x08\x00'


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)