Search code examples
pythonpython-2.7bit-manipulationctype

python ctypes bitwise data packing


item = -35519      
data_in = ctypes.c_int16(item)
data_pkd = (ctypes.c_int32(0) | data_in)

I am getting below error

data_pkd = (ctypes.c_int32(0) | data_in)
TypeError: unsupported operand type(s) for |: 'c_long' and 'c_short'
|31||30|    29  28  27  26  25  24  23  22  21  20  19  18  17  16| 15  14  13  12  11  10  9   8   7   6   5   4   3   2   1   0|
|P|M|------------------unused-------------------------------------|------------------------------item----------------------------|

I Intent to send 32-bit test data to a C application accepting int32 as input, mentioned in the above data format.

Thanks


Solution

  • You don't need bitwise-or, just packing the 16-bit value into a 32-bit one, i.e. a promotion:

    data_pkd = ctypes.c_int32(data_in.value)
    

    To actually perform bitwise-or on ctypes values, operate on their value attribute:

    x = ctypes.c_int16(...)
    y = ctypes.c_int32(...)
    data_pkd = ctypes.c_int32(x.value | y.value)