0

Say I have a byte array like so

 data = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])

 string_data = str(data)

 print(string_data)
 # "b'\\x13\\x00\\x00\\x00\\x08\\x00'"

I want back byte array from string of data

data = string_of_byte_array_to_byte_array(string_data)

print(data)
# b'\x13\x00\x00\x00\x08\x00'
1
  • Note that str(some_bytes) is almost never the right thing to do in Python 3. Commented Aug 7, 2021 at 15:45

3 Answers 3

2

ast.literal_eval will undo str on a bytes object:

>>> data = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> s = str(data)
>>> s
"b'\\x13\\x00\\x00\\x00\\x08\\x00'"
>>> import ast
>>> ast.literal_eval(s)
b'\x13\x00\x00\x00\x08\x00'

But there are better ways to view byte data as a hexadecimal string:

>>> data.hex()
'130000000800'
>>> s = data.hex(sep=' ')
>>> s
'13 00 00 00 08 00'
>>> bytes.fromhex(s)
b'\x13\x00\x00\x00\x08\x00'
1

You can use ast.literal_eval to revert the string to bytes. (Thank you at Matiiss and Mark Tolonen for pointing out the problems with the eval method)

from ast import literal_eval

data = literal_eval(data_string)
1
  • 1
    you should add tho that using eval is not safe
    – Matiiss
    Commented Aug 7, 2021 at 15:27
1
a_string = �?abc’
encoded_string = a_string. encode()
byte_array = bytearray(encoded_string)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.