Ludovic Guerra
Ludovic Guerra

Reputation: 350

Insert element on list, with index contain in a list

I want to implements a byte stuffing.
For this I have an escape characters and a end frame defined.
For each time I found an end frame, I must change the value of the end frame (with a bitwise operation) and add before an escape character.

I should also check for escape characters, but I will do it in a second times
.

frame = bytearray(b'\xae\xde\xad\xbe\xef\xde\xad\xbe\xef')
end_frame = bytearray(b'\xde\xad\xbe\xef')
esc = bytearray(b'\xaa\xbb\xcc\xdd')
end_frame_index = [i for i, x in enumerate(frame) if frame[i:i + len(end_frame)] == end_frame]
for i in range(len(frame)):
    if i in end_frame_index:
        for j in range(i,i+len(end_frame)):
            frame[j] = ~frame[j] & 0xFF

So the frame is the frame I want to send. end_frame the frame that I must find, and the esc what I want to add.
So first I find in end_frame_index all iteration of the end frame in my main frame.
Then i change the value of all end frame found.

Now I want to add the esc character to all iteration found.

The ouput I want is this one:

bytearray(b'\xae\xaa\xbb\xcc\xdd\x21\x52\x41\x10\xaa\xbb\xcc\xdd\x21\x52\x41\x10')

My problem is that the list will be growing every time I had the esc character.

So how can I handle this ?

Upvotes: 0

Views: 58

Answers (2)

Jon Clements
Jon Clements

Reputation: 142156

bytearrays support the .replace method, so you can pre-compute a new end_frame to act as a replacement, then use that and prepend the esc variable, eg:

frame = bytearray(b'\xae\xde\xad\xbe\xef\xde\xad\xbe\xef')
end_frame = bytearray(b'\xde\xad\xbe\xef')
# compute new end frame
new_end_frame = bytearray(~el & 0xFF for el in end_frame)
esc = bytearray(b'\xaa\xbb\xcc\xdd')

Now create the output:

output = frame.replace(end_frame, esc + new_end_frame)

Which gives you:

bytearray(b'\xae\xaa\xbb\xcc\xdd!RA\x10\xaa\xbb\xcc\xdd!RA\x10')

Upvotes: 1

Ludovic Guerra
Ludovic Guerra

Reputation: 350

Here a solution in "C way" but that is not really pythonic

frame = bytearray(b'\xae\xde\xad\xbe\xef\xde\xad\xbe\xef')
end_frame = bytearray(b'\xde\xad\xbe\xef')
esc = bytearray(b'\xaa\xbb\xcc\xdd')
new_array = bytearray()
index_new_array = 0
index_frame = 0
while index_frame < len(frame):
    if frame[index_frame:index_frame + len(end_frame)] == end_frame:
        new_array.extend(esc)
        index_new_array += len(esc)
        new_array.extend([(~x & 0xff) for i, x  in enumerate(frame[index_frame:index_frame + len(end_frame)])])
        index_new_array += len(esc)
        index_frame += len(end_frame) - 1
    else:
        new_array.append(frame[index_frame])
        index_new_array += 1

    index_frame += 1
print(new_array.hex())

Upvotes: 0

Related Questions