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 []
.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
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.
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.
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.
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