Help/example of bit testing
Mirko Liß
mliss at exmail.de
Sat Dec 9 17:15:19 EST 2000
Bryan Webb wrote:
> I am reading a file (binary)of 1024 char recs (bitmaps) . I can read the
> file , bit im having trouble finding examples of testing bits. I need to
> look at each bit of the above record.
Supposedly, you already use struct.unpack() from the struct-module to
convert
chunks of your binary string data into numbers.
If speed and memory doesn't matter much, you might want to store
the bits in a user-defined list-object, for example:
>>> import UserList
>>> class Bitfield(UserList.UserList):
... def __init__(self,number):
... self.data = []
... while number:
... self.data.append(number & 1)
... number = number >> 1
... def __getitem__(self, key):
... if key < len(self.data):
... return self.data[key]
... else:
... return 0
...
>>> bf=Bitfield(0xc02)
>>> bf
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]
bf[0] is the least significant bit.
Because of the redefined __getitem__() method, you don't need to worry
about
illegal indices:
>>> len(bf),bf[15],bf[13],bf[12],bf[11]
(12, 0, 0, 0, 1)
You might as well redefine the __getslice__() method if you need to look
at
various bits at once.
I hope you like this,
Mirko Liss
More information about the Python-list
mailing list