How to dynamically tranform data with python construct parser

268 Views Asked by At

I want to dynamically transform binaries data with the construct python lib.

Here is a simple struct:

import construct

data = construct.Struct(
    x = construct.Int16ul
)

I would like to divide (applying a shift) the x data by 128 .

e.g: if x is equals to 1, I would like to have the value 0.0078125 (1 / 128).

I tried to apply a function with the * operator, the function is called but the value is not saved in the x attribute.

import construct

def shift(value, context):
    return value / 128

data = construct.Struct(
    x = construct.Int16ul * shift
)
1

There are 1 best solutions below

0
On

Use the ExprAdapter to apply custom encode and decode functions.

https://construct.readthedocs.io/en/latest/api/core.html#construct.core.ExprAdapter

import construct

def unshift(value, context):
    return value / 128

def shift(value, context):
    return value * 128

data = construct.Struct(
    x = construct.ExprAdapter(construct.Int16ul, unshift, shift)
)