Packing byte fields and an array object into struct

krishna2prasad at gmail.com krishna2prasad at gmail.com
Wed Nov 13 15:41:03 EST 2013


Thanks for your reply Ned!

I tried this your suggestion and this is what it complains...

os_inst_bytes = struct.pack('7BI512s', 0, 0x51, 0x10, 5, 0, 0xD, 0x80, 0, '')

---------------------------------------------------------------------------
error                                     
Traceback (most recent call last)
<ipython-input-6-d36f45a8d3e6> in <module>()
----> 1 os_inst_bytes = struct.pack('7BI512s', 0, 0x51, 0x10, 5, 0, 0xD, 0x80, 0, "")

error: argument for 's' must be a bytes object

In [7]: 


And about the bytearray() call, I want to pass a mutable object to the IOCTL to be able to get the data back from the driver. Without bytearray(), the ioctl with mutable flag set to 1 would complain.

I tried to use the p format specifier with pack after converting the array object to byte stream. Packing seems fine. However, I cant seem to unpack.

In [1]: import array

In [2]: import struct

In [3]: data        = array.array('B', (1 for x in range(5)))

In [4]: data_bytes  = data.tobytes()

In [5]: os_inst_bytes = struct.pack('7BIp', 0, 0x51, 0x10, 5, 0, 0xD, 0x80, 0, data_bytes) 

In [6]: 

In [6]: os_inst = bytearray(os_inst_bytes)

In [7]: result = struct.unpack('7B', os_inst[0:7])

In [8]: print(result)
(0, 81, 16, 5, 0, 13, 128)

In [9]: result = struct.unpack('I', os_inst[7:11])

In [10]: print(result)
(0,)

In [11]: result = struct.unpack('5s', os_inst[11:16])
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-11-da14a6693435> in <module>()
----> 1 result = struct.unpack('5s', os_inst[11:16])

error: unpack requires a bytes object of length 5

In [12]: 





More information about the Python-list mailing list