Home > OS >  Convert bytearray to array.array('B')
Convert bytearray to array.array('B')

Time:10-28

I have an image data, which primarily looks like:

array('B', [255,216,255...])

It is of type array.array('B')

Since this data is to be sent over a communication channel, It is necessary to convert this data to type: bytearray.

I converted the data to bytearray:

data1 = bytearray(CompressedImage.data)

However, I now need to get the original array.array('B') form of the data.

So far, I found byte() and decode() function,s but I am still unable to deserialize the original data form.

CodePudding user response:

Encoding/decoding is not needed since we are dealing with raw bytes here.

You can pass the bytearray directly to array initializer. You'll still need to specify the type code in the initializer, since the raw bytes themselves can't tell you. "B" for 1 byte unsigned int, i.e. 8-bit colour depth.

>>> from array import array
>>> a = array("B", [255, 216, 255])
>>> data1 = bytearray(a)
>>> a1 = array("B", data1)
>>> a1 == a
True

If you have an existing array instance to populate, you can use frombytes

>>> a2 = array("B")
>>> a2.frombytes(data1)
>>> a == a1 == a2
True
  • Related