Convert list of byte strings to bytearray (byte stream)

我们两清 提交于 2019-12-19 04:21:07

问题


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.


回答1:


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.




回答2:


hexlist = ["a9", "00", "85", "c6"]
ba = bytearray(h.decode("hex") for h in hexlist)

See also bytearray.fromhex:

bytearray.fromhex(string) -> bytearray

Create a bytearray object from a string of hexadecimal numbers. Spaces between two numbers are accepted. Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\xb9\x01\xef').




回答3:


Refer to :

char* PyByteArray_AsString(PyObject *bytearray) Return the contents of bytearray as a char array after checking for a NULL pointer

from the python doc reference



来源:https://stackoverflow.com/questions/8382127/convert-list-of-byte-strings-to-bytearray-byte-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!