Python Convert Bytearray to Numbers in List

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 [].

1

4 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]        

Indexing a bytearray results in unsigned bytes.

>>> pt[0]
50
>>> pt[5]
90

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.

I was looking for an answer to 'How may you convert binary into decimal values?' and found this question, so I want to complete Malik Brahimi's answer as much as I can.

Basically, what you can do is to create a list of ones and then iterate through them in order to create decimal list:

b_list = ['0', '1', '10', '11', '100', '101'] # Note, that values of list are strings
res = [int(n, 2) for n in b_list] # Convert from base two to base ten
print(res)

# Output:
# User@DESKTOP-CVQ282P MINGW64 ~/desktop
# $ python backpool.py
# [0, 1, 2, 3, 4, 5]

You may note, that we can use this way to convert values with different bases: binary, hex and so on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.