What is the Pythonic way to implement a simple FSM?

后端 未结 7 1627
猫巷女王i
猫巷女王i 2021-01-31 21:50

Yesterday I had to parse a very simple binary data file - the rule is, look for two bytes in a row that are both 0xAA, then the next byte will be a length byte, then skip 9 byte

相关标签:
7条回答
  • 2021-01-31 22:45

    You can use regexps. Something like this code will find the first block of data. Then it's just a case of starting the next search from after the previous match.

    find_header = re.compile('\xaa\xaa(.).{9}', re.DOTALL)
    m = find_header.search(input_text)
    if m:
        length = chr(find_header.group(1))
        data = input_text[m.end():m.end() + length]
    
    0 讨论(0)
提交回复
热议问题