Python byte array

How can I represent an array of bytes (as in Java with a byte []) in Python? I will need to send it by wire using gevent.

byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00}; 
+43
python byte gevent
Sep 11 '11 at 18:45
source share
4 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]) 

It’s more convenient for me 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' 
+42
Sep 11 '11 at 18:50
source share

Just use bytearray (Python 2.6 and later), which represents a volatile byte sequence

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

Indexing gets and sets individual bytes

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

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

 >>> bytes(key) '\x13\xff\x00\x00\x08\x00' 
+21
Sep 11 '11 at 19:06
source share

An alternative that also has the added benefit of being easy to record your result:

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

allows simple substitutions as follows:

 hexs = "13 00 00 00 08 {:02X}".format(someByte) logging.debug(hexs) key = bytearray.fromhex(hexs) 
+4
Jul 11 '15 at 16:27
source share

Dietrich's answer is probably exactly what you need for what you describe sends bytes, but a closer analogue to the code you provided, for example, would use the bytearray type.

 >>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00]) >>> bytes(key) b'\x13\x00\x00\x00\x08\x00' >>> 
+1
Sep 11 '11 at 18:58
source share



All Articles