Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert bytearray into bytearray Python

Tags:

python

insert

I'm trying to insert one byte array into another at the beginning. Here's a simple example of what I'm trying to accomplish.

import struct
a = bytearray(struct.pack(">i", 1))
b = bytearray(struct.pack(">i", 2))
a = a.insert(0, b)
print(a)

However this fails with the following error:

a = a.insert(0, b) TypeError: an integer is required

like image 412
Russell Avatar asked Sep 20 '17 20:09

Russell


People also ask

How do you declare Bytearray in Python?

Python | bytearray() functionbytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256. Returns: Returns an array of bytes of the given size. source parameter can be used to initialize the array in few different ways.

How do you add two bytes in Python?

To join a list of Bytes, call the Byte. join(list) method. If you try to join a list of Bytes on a string delimiter, Python will throw a TypeError , so make sure to call it on a Byte object b' '. join(...)

What is Bytearray in Python?

Python bytearray() Function The bytearray() function returns a bytearray object. It can convert objects into bytearray objects, or create empty bytearray object of the specified size.


1 Answers

bytearray is a sequence-type, and it supports slice-based operations. The "insert at position i" idiom with slices goes like this x[i:i] = <a compatible sequence>. So, for the fist position:

>>> a
bytearray(b'\x00\x00\x00\x01')
>>> b
bytearray(b'\x00\x00\x00\x02')
>>> a[0:0] = b
>>> a
bytearray(b'\x00\x00\x00\x02\x00\x00\x00\x01')

For the third position:

>>> a
bytearray(b'\x00\x00\x00\x01')
>>> b
bytearray(b'\x00\x00\x00\x02')
>>> a[2:2] = b
>>> a
bytearray(b'\x00\x00\x00\x00\x00\x02\x00\x01')

Note, this isn't equivalent to .insert, because for sequences, .insert inserts the entire object as the ith element. So, consider the following simple example with lists:

>>> y = ['a','b']
>>> x.insert(0, y)
>>>
>>> x
[['a', 'b'], 1, 2, 3]

What you really wanted was:

>>> x
[1, 2, 3]
>>> y
['a', 'b']
>>> x[0:0] = y
>>> x
['a', 'b', 1, 2, 3]
like image 153
juanpa.arrivillaga Avatar answered Sep 28 '22 10:09

juanpa.arrivillaga