Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte Array in Python

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}; 
like image 972
d0ctor Avatar asked Sep 11 '11 18:09

d0ctor


People also ask

What is byte array in Python?

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.

What is an byte array?

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.

What is byte and byte array?

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.

Is byte [] same as string?

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.


2 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'\x13\0\0\0\x08\0'  # Python 2 key = '\x13\0\0\0\x08\0' 
like image 158
Dietrich Epp Avatar answered Sep 28 '22 05:09

Dietrich Epp


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' 
like image 40
Scott Griffiths Avatar answered Sep 28 '22 05:09

Scott Griffiths