Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a list of characters and bytes into a list of pure bytes?

Tags:

python

list

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?

like image 451
user791953 Avatar asked Jan 27 '26 03:01

user791953


1 Answers

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']
like image 195
Hari Menon Avatar answered Jan 28 '26 16:01

Hari Menon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!