On Mar 11, 5:49 pm, none <""luca\"@(none)"> wrote: > i need to interface python with a bitpacked data file, > the structure recorded in the file is the following: > > struct { > var_1 4bit > var_2 6bit > var_3 2bit > var_3 4bit > > } > > how can read the struct and convert data into dictionary > > Thnx
I noticed that you have a 4+6+2+4=16 bits total. That's a short (unsigned) integer that you'd have to unpack using the stuct module's unpack method. The format string would be 'H'. Unpack using big endian. Here is a quick example for you: ------------------------------ [EMAIL PROTECTED]:~$ ipython >>> from struct import pack,unpack >>> m1='1'*4 >>> m2='1'*6 >>> m3='1'*2 >>> m4='1'*4 >>> m1,m2,m3,m4 ('1111', '111111', '11', '1111') >>> #define some data >>> idata=int('1100101011111110',2) >>> idata 51966 >>> #pack as a 16 bit integer (usigned int) >>> packed=pack('>H',idata) >>> #note > means big endian >>> packed '\xca\xfe' >>> #oh, wow it spells cafe! ;-) >>> #now unpack >>> unpacked=unpack('>H',packed) >>> unpacked (51966,) >>> odata=unpacked[0] >>> vars=[] >>> for mask in (m4,m3,m2,m1): ....: vars.append(odata & int(mask,2) ) ....: odata>>=len(mask) ....: >>> vars [14, 3, 43, 12] >>> vars.reverse() >>> vars [12, 43, 3, 14] ------------------------------------------------- So in binary v1='1100' v2='101011' v3='11' v4='1110' If you concatenate them: 1100101011111110 you get the original idata... Hope this helped, Nick Vatamaniuc -- http://mail.python.org/mailman/listinfo/python-list