简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM