Convert byte string to bytes or bytearray

纵饮孤独 提交于 2019-12-19 05:47:28

问题


I have a string as follows:

  b'\x00\x00\x00\x00\x07\x80\x00\x03'

How can I convert this to an array of bytes? ... and back to a string from the bytes?


回答1:


in python 3:

>>> a=b'\x00\x00\x00\x00\x07\x80\x00\x03'
>>> b = list(a)
>>> b
[0, 0, 0, 0, 7, 128, 0, 3]
>>> c = bytes(b)
>>> c
b'\x00\x00\x00\x00\x07\x80\x00\x03'
>>>



回答2:


From string to array of bytes:

a = bytearray.fromhex('00 00 00 00 07 80 00 03')

or

a = bytearray(b'\x00\x00\x00\x00\x07\x80\x00\x03')

and back to string:

key = ''.join(chr(x) for x in a)


来源:https://stackoverflow.com/questions/35310695/convert-byte-string-to-bytes-or-bytearray

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