Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python convert bytearray to numbers in list

For the following python codes:

pt  = bytearray.fromhex('32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34')
state = bytearray(pt)

If I use:

print state

It gives out 2Cö¨ˆZ0?11˜¢à74

Then how to recover the content in the bytearray? For example, to put them in a list like [].

like image 864
chrisTina Avatar asked Feb 12 '15 21:02

chrisTina


People also ask

How do you convert Bytearray?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

How do you decode Bytearray in Python?

Using the decode() Function to convert Bytearray to String in Python. An alternative way to convert a bytearray to string is by using the decode() method. The decode() method, when invoked on a bytearray object, takes the encoding format as input and returns the output string.

What does Bytearray return Python?

bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256. Returns: Returns an array of bytes of the given size. source parameter can be used to initialize the array in few different ways.


3 Answers

You can convert between a bytearray and list using the python built in functions of the same name.

>>> x=[0,1,2,3,4]      # create a list 
>>> print x
[0, 1, 2, 3, 4]
>>> y = bytearray(x)   # convert the list to a bytearray    
>>> print y
(garbled binary)               <-- prints UGLY!
>>> z = list(y)        # convert the bytearray back into a list
>>> print z
[0, 1, 2, 3, 4]        
like image 78
D M Lowe Avatar answered Sep 21 '22 12:09

D M Lowe


Indexing a bytearray results in unsigned bytes.

>>> pt[0]
50
>>> pt[5]
90
like image 21
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 12:09

Ignacio Vazquez-Abrams


You can make your own method with simple string methods:

string = '32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34'
number = [int(i, 16) for i in string.split()]

Now you have a list of the converted numbers as you wanted.

like image 31
Malik Brahimi Avatar answered Sep 21 '22 12:09

Malik Brahimi