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'
vbnr
  • 307
  • 2
  • 5
  • 14

3 Answers3

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'
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
1
a_string = ‘abc’
encoded_string = a_string. encode()
byte_array = bytearray(encoded_string)
BlackMath
  • 1,708
  • 1
  • 11
  • 14
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)
fsimonjetz
  • 5,644
  • 3
  • 5
  • 21