I have a list which is a mixture of characters and bytes, which looks like this :
myData = ['a', '\x65', 'B', '\x66\x69', 'C']
I want to convert this list into a byte array, so this :
myByteArray = ['\x61' , '\x65', '\x42', '\x66', '\x69', '\x43']
What I have tried so far is a simple display on myData --
myData = ['a', '\x65', 'B', '\x66\x69', 'C']
print " ".join(hex(ord(n)) for n in myData)
Since there is an element in the array that happens to be two bytes, it throws this error:
Traceback (most recent call last):
File "./test.py", line 3, in <module>
print " ".join(hex(ord(n)) for n in myData)
File "./test.py", line 3, in <genexpr>
print " ".join(hex(ord(n)) for n in myData)
TypeError: ord() expected a character, but string of length 2 found
How can I convert my original list, myData, into a byte array, myByteArray?
You can merge them all and split again to get the individual chars, like:
output_list = [hex(ord(c)) for c in ''.join(myData)]
Trying it out,
>>> myData = ['a', '\x65', 'B', '\x66\x69', 'C']
>>> [hex(ord(c)) for c in ''.join(myData)]
['0x61', '0x65', '0x42', '0x66', '0x69', '0x43']
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