Convert list of byte strings to bytearray (byte stream)
14,781
hexstrings = ["DE", "AD", "BE", "EF"] # big-endian 0xDEADBEEF
bytes = bytearray(int(x, 16) for x in hexstrings)
bytes = bytearray.fromhex("".join(hexstrings)) # Python 2.6 may need u""
If you've got a lot of 'em, it might be worthwhile to see which of those is fastest.
Author by
Lance Roberts
Control Systems Engineer. Most people want to stick their head in the sand and ignore problems, in an effort to avoid conflict. I refuse to be that passive person. Problems are there to be fixed, which means that first they have to identified. Denial is not just a river in Egypt.
Updated on November 01, 2022Comments
-
Lance Roberts over 1 year
I have a list of hex strings representing bytes, of the form "FF". I want to convert the whole list to a byte stream so I can send it over a socket (Python 3). It looks like the bytearray type would work, but I can't find any way to directly convert the list to a bytearray.
I can do it manually in a loop, but figure there must be a better Python way to do this.
-
Lance Roberts over 12 yearsI'm looking to go the other direction.
-
John Machin over 12 yearsFirst code comment:
0xDEADBEEF
is an integer which relates tohexstrings
only on a bigendian machine. Second code comment: Your code works with python 2.7 without change; it would need major surgery to get it to work on earlier versions e.g."".join([chr(int(x, 16)) for x in hexstrings])
will do the job for Python 2.1 to 2.7 inclusive. -
kindall over 12 yearsThe first comment was merely an opportunity to write "Ox Dead Beef" in hex, but you are technically correct -- the best kind of correct! And "big-endian ox dead beef" is arguably even funnier. :-) On the second, it was actually Python 2.6 that insisted on having a Unicode string there, but that seems to be a bug. 2.7 behaves as you state and I've changed that. (
bytearray
was introduced in 2.6, just for the record.)