Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte string to bytes or bytearray

Tags:

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?

like image 566
IAbstract Avatar asked Feb 10 '16 09:02

IAbstract


People also ask

What is the difference between bytes and Bytearray?

The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.

Is byte [] same as string?

Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.

What is Bytearray used for?

The Python bytearray() function converts strings or collections of integers into a mutable sequence of bytes. It provides developers the usual methods Python affords to both mutable and byte data types.


2 Answers

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'
>>>
like image 80
steel.ne Avatar answered Sep 20 '22 12:09

steel.ne


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)
like image 20
RafaelCaballero Avatar answered Sep 18 '22 12:09

RafaelCaballero