Convert byte string to bytes or bytearray
61,766
Solution 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'
>>>
Solution 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)
Related videos on Youtube
Author by
IAbstract
From grass roots AppleSoft Basic and Assembly, to VB6 and C#/VB.NET - I have seen coding evolve into something anyone can do. However, it takes serious dedication to become a programmer. I have been working with MEF to better learn usage and techniques. I am also interested in open source projects and looking for opportunities with XNA. I have experience with TCP, Sql and MySql, and Lua integration. Also, I am looking to gain some experience with Ruby. Never 'try', always 'do'. 'Try' is an ingredient for failure - paraphrased from 'I Love You Man'. #SOreadytohelp
Updated on February 10, 2020Comments
-
IAbstract over 4 years
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?
-
IAbstract over 8 yearsSo I need to replace
\x
with a space first? -
IAbstract over 8 yearsI just realized that
b'\x00\x00\x00\x00\x07\x80\x00\x03'
is iterable. Thanks. -
RafaelCaballero over 8 yearsNo, just a = bytearray(b'\x00\x00\x00\x00\x07\x80\x00\x03')
-
RafaelCaballero over 8 yearsBe careful: using lists
b = list(a)
allows doing (by mistake)b[5] = 1550
, because b is not an array of bytes. However, ifb = bytearray(a)
, thenb[5] = 1550
gives an error, because 1550 is not a byte. -
Sadique Khan over 2 years'str' object cannot be interpreted as an integer