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'
3 Answers 3
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'
answered Aug 7, 2021 at 15:35
Mark Tolonen
181k26 gold badges184 silver badges279 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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)
answered Aug 7, 2021 at 15:26
fsimonjetz
5,7923 gold badges7 silver badges23 bronze badges
1 Comment
Matiiss
you should add tho that using
eval is not safea_string = ‘abc’
encoded_string = a_string. encode()
byte_array = bytearray(encoded_string)
answered Aug 7, 2021 at 15:24
BlackMath
1,8561 gold badge13 silver badges15 bronze badges
Comments
lang-py
str(some_bytes)is almost never the right thing to do in Python 3.