getting at individual bits inside byte field: struct module : bitwise operator

Mark Tolonen M8R-yfto6h at
Tue Feb 24 05:27:33 CET 2009

"harijay" <harijay at> wrote in message 
news:4c7d58a1-830f-4f02-ba07-aa4910f5f4e9 at
> In my last post I had asked about reading data from a binary file
> using the struct module.
> Thanks to some excellent help , I have managed to read in
> successfully
> most of the header of this binary format that I want to parse.  These
> are some time-voltage traces from a digital
> to analog converter for my experiments. The output is according to a
> format
> mentioned here : (
> I have a question about how to bitmask a bunch of bytes read in from
> such a binary formatted file .
> For eg the spec says the first two bytes have different parameters in
> different bits .
> Byte 1                                                  Byte 0
> SN16 SD9        SD8     SD7     SD6     SD5     SD4     SD3
> SD2     SD1     SD0     T4      T3      T2      T1      T0
> I am reading in the two bytes using the following code
> import struct
> element1_format = struct.Struct("<H")
> (element1,) = element1_format.unpack(
> Now element1 has type "str" . How do I apply a bitmask to this to get
> at information in the component bits .
> Since the entire file format has many such bitmasked fields and since
> this is my first venture into binary formats and c-type structs , I
> wanted to know how to read values inside a byte using python.
> My few tries at using bitwise operators ( element1 & 0x001f) are
> frustrated by messages that say " unsupported operand type(s) for &:
> 'str' and 'int' " .
> How can I keep my string objects as bits and apply bitmasks to them
> Any help in this will be greatly appreciated.
> Thanks
> hari

Please post a small example that fails as you describe.  From your example, 
element1 should be an int (unpacked from two bytes), and there is no f 
defined.  Without the actual code we can't figure out what you are doing 

This works as expected:

>>> import struct
>>> format = struct.Struct("<H")
>>> (element1,) = format.unpack('aa') # a two-byte string to unpack
>>> print hex(element1)
>>> print element1 & 0x1f


More information about the Python-list mailing list