Last active
November 28, 2019 11:30
-
-
Save csghone/8d6624eea6e804b5d8d3b0ce5d2d3fd0 to your computer and use it in GitHub Desktop.
Parse binary data into structures using structures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # https://github.com/malinoff/structures - not actively developed | |
| import structures | |
| from structures import Repeat, Struct, Bytes, Integer, Contextual, RepeatExactly, BitFields, Const, Computed | |
| class Test(Struct): | |
| const_val = Const(b'AB') | |
| bit_fields = BitFields('b1: 4, b2: 3, b3: 1') | |
| variable_array_length = Integer(1) | |
| computed_variable = Computed(lambda x: x["variable_array_length"] * 100) | |
| variable_array = structures.If( | |
| lambda x: True, Contextual(RepeatExactly, lambda x:(Integer(1), x['variable_array_length']))) | |
| # Without 'If' | |
| # variable_array = structures.Contextual(RepeatExactly, lambda x:(Integer(1), x['variable_array_length'])) | |
| fixed_array = RepeatExactly(Integer(2, byteorder='big', signed=False), 2) | |
| data1 = b'AB\xAA\x01\xAB\x01\x02\x03\x04' | |
| data2 = b'AB\xAA\x02\xAB\xCD\x05\x06\x07\x08' | |
| print(Test().parse(data1)) | |
| # {'const_val': b'AB', 'bit_fields': {'b1': 10, 'b2': 5, 'b3': 0}, 'variable_array_length': 1, computed_variable': 100, 'variable_array': [171], 'fixed_array': [258, 772]} | |
| print(Test().parse(data2)) | |
| # {'const_val': b'AB', 'bit_fields': {'b1': 10, 'b2': 5, 'b3': 0}, 'variable_array_length': 2, computed_variable': 100, 'variable_array': [171, 205], 'fixed_array': [1286, 1800]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment