Home > Enterprise >  Python - bytearray read with parameters
Python - bytearray read with parameters

Time:02-22

I have a project where I read a bytearray this way to indicate where I start and where I end :

data = array[5:9]

But of course these address might change. How can I use variables/parameters to retrieve dynamically my data from the array ? Something like that ?:

start_byte = 5
end_byte = 9

data = array[start_byte:end_byte]

I'm currently experiencing some issue with this and wanted some advice.

Thank you to everyone who will help.

CodePudding user response:

Your solution seems fairly optimal to me if I understand your question correctly. I don't know your level of knowledge in python but you might have problem with slicing the bytearray which is essentially the same as slicing a list. So let me give you an example

a = [0, 1, 2, 3, 4, 5]
print(a[0:2]) --> prints [0, 1]
print(a[2:4]) --> prints [2, 3]

For practical cases you can image it is just a range function, it is a left closed and right opened interval [start_index, end_index). Making it equivalent to the following:

a = [0, 1, 2, 3, 4, 5]
b = []
for i in range(start_index, end_index):
    b.append(a[i])
  • Related