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:
because the search starts at
start_pos, and ifmsg_start_tokenis found at that position, find will returnstart_posof course.As for the difference between
.index()and.find();.index()raises aValueErrorexception if the substring is not found, while.find()returns-1instead.