0

I have a string of bytearray which i want to convert to bytearray in python 3

For example,

x = "\x01\x02\x03\x04"

I get the x variable from server, it is a string but content is byte array, how to convert it to byte array. Really stuck at it. Thanks

benvc
  • 14,448
  • 4
  • 33
  • 54
chink
  • 1,505
  • 3
  • 28
  • 70
  • 1
    You can ``encode`` the string to a bytes object. It would be easier to directly operate on the initial data - TCP (etc.) only transmits bytes, so having a string means you already converted it *from* bytes to a string. – MisterMiyagi Aug 01 '19 at 16:06
  • 1
    Possible duplicate of [Python: convert string to byte array](https://stackoverflow.com/questions/11624190/python-convert-string-to-byte-array) – DavidW Aug 02 '19 at 15:54
  • 1
    Also duplicate of https://stackoverflow.com/questions/32675679/convert-binary-string-to-bytearray-in-python-3 https://stackoverflow.com/questions/29177788/python-string-to-bytearray-and-back – DavidW Aug 02 '19 at 15:55
  • Also: [Python convert strings of bytes to byte array](https://stackoverflow.com/q/51754731/2745495) – Gino Mempin Aug 03 '19 at 01:27

3 Answers3

2

You can encode a string to a bytes object and convert that to a bytearray, or convert it directly given some encoding.

x = "\x01\x02\x03\x04"      # type: str
y = x.encode()              # type: bytes
a = bytearray(x.encode())   # type: bytearray
b = bytearray(x, 'utf-8')   # type: bytearray

Note that bytearray(:str, ...) is specified to use str.encode, so the later two practically do the same. The major difference is that you have to specify the encoding explicitly.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
2

You can use ord to convert each byte in the string to an integer. bytearray takes an iterable of integers as an argument, so

x = "\x01\x02\x03\x04"
b = bytearray(ord(c) for c in x) # bytearray(b'\x01\x02\x03\x04')
acurtis
  • 109
  • 3
2

Try this :

x = bytes(x, 'utf-8')

Now type(x) is bytes.

Rumi
  • 196
  • 7