将字节字符串转换为字节或bytearray

时间:2021-08-30 18:25:48

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?

如何将其转换为字节数组? ...并返回字节中的字符串?

2 个解决方案

#1


11  

in python 3:

在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


1  

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)

#1


11  

in python 3:

在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


1  

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)