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 bytearray() Function The bytearray() function returns a bytearray object. It can convert objects into bytearray objects, or create empty bytearray object of the specified size.
A consecutive sequence of variables of the data type byte, in computer programming, is known as a byte array. An array is one of the most basic data structures, and a byte is the smallest standard scalar type in most programming languages.
The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size. The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.
Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.
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'
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'\x13\x00\x00\x00\x08\x00')
Indexing get and sets the individual bytes
>>> key[0] 19 >>> key[1]=0xff >>> key bytearray(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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With