Python3 search in bytearray

I have this weird problem using find () / index () (don't know if there is a difference between the two) with bytear.

I am working with a binary file, I downloaded it as bytesarray, and now I need to find markers indicating the beginning of the message and the end of the message. Everything works fine with finding the beginning of a message (0x03 0x02), but I continue to get the same position where I started looking when I was looking for the end (0x00)

msg_start_token = bytearray((int(0x03), int(0x02))) msg_end_token = bytes(int(0x00)) def get_message(file,start_pos): msg_start = file.find(msg_start_token,start_pos) + 2 print(hex(msg_start)) msg_end = file.find(msg_end_token,msg_start) print(hex(msg_end)) msg = file[msg_start:msg_end] print(msg) return (msg, msg_end) 

I still haven’t worked with binary files, so I don’t know, maybe I really miss something really simple.

+4
source share
1 answer

You need to start the search in the following position, so search at:

 file.find(msg_start_token, start_pos + 1) 

because the search starts with start_pos , and if msg_start_token is in that position, find will return start_pos , of course.

Regarding the difference between .index() and .find() ; .index() throws a ValueError exception if no substring is found, and .find() returns -1 instead.

+2
source

All Articles