Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 searching in bytearray

I have this strange problem with using find()/index() (don't know if there is any difference between them) with bytesarray.

I'm working with binary file, I have loaded it as bytesarray and now I need to find tokens that indicate beginning of message and end of message. Everything works fine with finding the beginning of message (0x03 0x02) but I keep getting the same position where I started searching when I search 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 haven't really worked with binary files before so I don't know maybe I'm missing something really simple in fact.

like image 910
J91321 Avatar asked Oct 06 '22 03:10

J91321


1 Answers

You need to start searching at the next position, so search at:

file.find(msg_start_token, start_pos + 1)

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

As for the difference between .index() and .find(); .index() raises a ValueError exception if the substring is not found, while .find() returns -1 instead.

like image 92
Martijn Pieters Avatar answered Oct 13 '22 10:10

Martijn Pieters